Created
August 8, 2016 21:36
-
-
Save f5io/3453f9a53af0213215f05fcd745471e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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