once.js 599 B

12345678910111213141516171819
  1. "use strict";
  2. /* tslint:disable no-invalid-this */
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.once = once;
  5. const instances = new WeakMap();
  6. /**
  7. * A class method decorator that limits a method to be called only once. All
  8. * subsequent calls will return the result of the first call.
  9. */
  10. function once(fn, context) {
  11. return function (...args) {
  12. let map = instances.get(this);
  13. if (!map)
  14. instances.set(this, (map = new WeakMap()));
  15. if (!map.has(fn))
  16. map.set(fn, fn.apply(this, args));
  17. return map.get(fn);
  18. };
  19. }