UNPKG

882 BJavaScriptView Raw
1const {Expression} = require('./lang');
2
3const 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
13const maybeMemoize = (testFunc, objFunc, primitiveFunc) => {
14 let funcOnObj; //eslint-disable-line prefer-const
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
25const memoizeExprFunc = (exprFunc, nonExprFunc) => maybeMemoize(t => t instanceof Expression, exprFunc, nonExprFunc);
26
27const memoizeNonPrimitives = (objFunc, primitiveFunc) => maybeMemoize(t => t && t === Object(t), objFunc, primitiveFunc);
28
29module.exports = {
30 memoizeNonPrimitives,
31 maybeMemoize,
32 memoizeExprFunc,
33 memoize
34};