Source: lib/util/lazy.js

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