memoize.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. /** Cache the latest result from calls to a function with any number of arguments */
  7. export function memoizeLatest<Args extends any[], T>(f: (...args: Args) => T): (...args: Args) => T {
  8. let lastArgs: any[] | undefined = void 0, value: any = void 0;
  9. return (...args) => {
  10. if (!lastArgs || lastArgs.length !== args.length) {
  11. lastArgs = args;
  12. value = f.apply(void 0, args);
  13. return value;
  14. }
  15. for (let i = 0, _i = args.length; i < _i; i++) {
  16. if (args[i] !== lastArgs[i]) {
  17. lastArgs = args;
  18. value = f.apply(void 0, args);
  19. return value;
  20. }
  21. }
  22. return value;
  23. };
  24. }
  25. /** Cache all results from calls to a function with a single argument */
  26. export function memoize1<A, T>(f: (a: A) => T): (a: A) => T {
  27. const cache = new Map<A, T>();
  28. return a => {
  29. if (cache.has(a)) return cache.get(a)!;
  30. const v = f(a);
  31. cache.set(a, v);
  32. return v;
  33. };
  34. }