Skip to content

Instantly share code, notes, and snippets.

@f5io
Created August 8, 2016 21:36
Show Gist options
  • Save f5io/3453f9a53af0213215f05fcd745471e3 to your computer and use it in GitHub Desktop.
Save f5io/3453f9a53af0213215f05fcd745471e3 to your computer and use it in GitHub Desktop.
const memoize = (fn) => {
const cache = new Map();
const memo = (...a) => {
const key = a.reduce((hash, val) =>
hash += val === Object(val) ?
JSON.stringify(val) :
val, '');
if (!cache.has(key)) cache.set(key, fn(...a));
return cache.get(key);
}
return Object.defineProperties(memo, {
length: { value: fn.length },
_cache: { value: () => cache }
});
}
const collatz = memoize(num =>
num !== 1 ?
[num].concat(collatz(num % 2 === 0 ? num / 2 : (3 * num) + 1)) :
num);
console.log(collatz(2345))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment