memoize3.js.flow 917 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // @flow strict
  2. /**
  3. * Memoizes the provided three-argument function.
  4. */
  5. export default function memoize3<
  6. A1: { ... } | $ReadOnlyArray<mixed>,
  7. A2: { ... } | $ReadOnlyArray<mixed>,
  8. A3: { ... } | $ReadOnlyArray<mixed>,
  9. R: mixed,
  10. >(fn: (A1, A2, A3) => R): (A1, A2, A3) => R {
  11. let cache0;
  12. function memoized(a1, a2, a3) {
  13. if (!cache0) {
  14. cache0 = new WeakMap();
  15. }
  16. let cache1 = cache0.get(a1);
  17. let cache2;
  18. if (cache1) {
  19. cache2 = cache1.get(a2);
  20. if (cache2) {
  21. const cachedValue = cache2.get(a3);
  22. if (cachedValue !== undefined) {
  23. return cachedValue;
  24. }
  25. }
  26. } else {
  27. cache1 = new WeakMap();
  28. cache0.set(a1, cache1);
  29. }
  30. if (!cache2) {
  31. cache2 = new WeakMap();
  32. cache1.set(a2, cache2);
  33. }
  34. const newValue = fn(a1, a2, a3);
  35. cache2.set(a3, newValue);
  36. return newValue;
  37. }
  38. return memoized;
  39. }