1 | const {Expression} = require('./lang');
|
2 |
|
3 | const memoize = func => {
|
4 | const cache = new WeakMap();
|
5 | return arg => {
|
6 | if (!cache.has(arg)) {
|
7 | cache.set(arg, func(arg));
|
8 | }
|
9 | return cache.get(arg);
|
10 | };
|
11 | };
|
12 |
|
13 | const maybeMemoize = (testFunc, objFunc, primitiveFunc) => {
|
14 | let funcOnObj;
|
15 | const funcOnMaybeObj = token => {
|
16 | if (testFunc(token)) {
|
17 | return funcOnObj(token);
|
18 | }
|
19 | return primitiveFunc(token);
|
20 | };
|
21 | funcOnObj = memoize(token => objFunc(token));
|
22 | return funcOnMaybeObj;
|
23 | };
|
24 |
|
25 | const memoizeExprFunc = (exprFunc, nonExprFunc) => maybeMemoize(t => t instanceof Expression, exprFunc, nonExprFunc);
|
26 |
|
27 | const memoizeNonPrimitives = (objFunc, primitiveFunc) => maybeMemoize(t => t && t === Object(t), objFunc, primitiveFunc);
|
28 |
|
29 | module.exports = {
|
30 | memoizeNonPrimitives,
|
31 | maybeMemoize,
|
32 | memoizeExprFunc,
|
33 | memoize
|
34 | };
|