UNPKG

1.01 kBJavaScriptView Raw
1// @flow
2// port from @deck.gl/core
3
4function isEqual(a: any, b: any) {
5 if (a === b) {
6 return true;
7 }
8 if (Array.isArray(a)) {
9 // Special treatment for arrays: compare 1-level deep
10 // This is to support equality of matrix/coordinate props
11 const len = a.length;
12 if (!b || b.length !== len) {
13 return false;
14 }
15
16 for (let i = 0; i < len; i++) {
17 if (a[i] !== b[i]) {
18 return false;
19 }
20 }
21 return true;
22 }
23 return false;
24}
25
26/**
27 * Speed up consecutive function calls by caching the result of calls with identical input
28 * https://en.wikipedia.org/wiki/Memoization
29 * @param {function} compute - the function to be memoized
30 */
31export default function memoize(compute: Function) {
32 let cachedArgs = {};
33 let cachedResult;
34
35 return (args: any) => {
36 for (const key in args) {
37 if (!isEqual(args[key], cachedArgs[key])) {
38 cachedResult = compute(args);
39 cachedArgs = args;
40 break;
41 }
42 }
43 return cachedResult;
44 };
45}