Skip to content

Instantly share code, notes, and snippets.

@tolotrasmile
Created December 3, 2019 13:55
Show Gist options
  • Save tolotrasmile/6047a650bc7cdebea790dd0f963fec23 to your computer and use it in GitHub Desktop.
Save tolotrasmile/6047a650bc7cdebea790dd0f963fec23 to your computer and use it in GitHub Desktop.
function memoize(fn) {
let cache = {}
return function (...args) {
if (cache[args]) {
return cache[args]
}
const res = fn.apply(this, args)
cache[args] = res
return res
}
}
const fib = memoize((n) => (n < 2) ? n : fib(n - 1) + fib(n - 2))
function assertion(condition, message = 'Assertion failed') {
if (!condition) {
throw message
}
}
console.time('fibonacci time');
assertion(fib(0) + fib(1) === fib(2))
console.timeEnd('fibonacci time');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment