callWithMemoize

by evgkch

Babel + JSX

const callWithMemoize = (size = 0) => {
	const cache = {};
  console.log(cache);
	return (fn, ...args) => {
  	const res = Safe.get(cache, args);
    if (res[0])
    {
    	console.log('already done!')
    	return res[1];
    }
    else
    {
    	console.log('new value!')
    	const val = Safe.set(fn(...args), res[1], res[2]);
      return val[1];
    }
  }
}

const Safe = {
  get: (target, [key, ...keys] = []) => {
   	return typeof target == 'object' && target != null
    	? target[key]
        ? Safe.get(target[key], keys)
        : [false, target, [key, ...keys]]
      : [true, target];
  },
  set: (value, target, [key, ...keys] = []) => {
		if (keys.length > 0)
    {
    	target[key] = { ...target[key] };
      Safe.set(value, target[key], keys);
    }
    else
    	target[key] = value;
    return [true, target[value]];
  }
};

const memoize = callWithMemoize();
const fn = (x, y) => x ** y;
memoize(fn, 1, 2)
memoize(fn, 1, 3)
memoize(fn, 4, 2)
memoize(fn, 4, 2)