Source: lib/util/lazy.js

  1. /** @license
  2. * Copyright 2016 Google LLC
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. goog.provide('shaka.util.Lazy');
  6. goog.require('goog.asserts');
  7. /**
  8. * @summary
  9. * This contains a single value that is lazily generated when it is first
  10. * requested. This can store any value except "undefined".
  11. *
  12. * @template T
  13. */
  14. shaka.util.Lazy = class {
  15. /** @param {function():T} gen */
  16. constructor(gen) {
  17. /** @private {function():T} */
  18. this.gen_ = gen;
  19. /** @private {T|undefined} */
  20. this.value_ = undefined;
  21. }
  22. /** @return {T} */
  23. value() {
  24. if (this.value_ == undefined) {
  25. // Compiler complains about unknown fields without this cast.
  26. this.value_ = /** @type {*} */ (this.gen_());
  27. goog.asserts.assert(
  28. this.value_ != undefined, 'Unable to create lazy value');
  29. }
  30. return this.value_;
  31. }
  32. /** Resets the value of the lazy function, so it has to be remade. */
  33. reset() {
  34. this.value_ = undefined;
  35. }
  36. };