Skip to content

Instantly share code, notes, and snippets.

@zachallaun
Created November 7, 2016 21:42
Show Gist options
  • Save zachallaun/5a1231623318de307f14a8cd0b218a02 to your computer and use it in GitHub Desktop.
Save zachallaun/5a1231623318de307f14a8cd0b218a02 to your computer and use it in GitHub Desktop.
// V1
var cache = {};
function paths(rights, downs) {
var key = rights + ',' + downs;
if (cache[key]) return cache[key];
if (rights === 0 || downs === 0) {
return 1;
}
var value = paths(rights - 1, downs) + paths(rights, downs - 1);
cache[key] = value;
return value;
}
console.log(paths(20, 20)); // 6
// V2
function memoize(fn) {
var cache = {};
return function (...args) {
var key = args.join(',');
if (cache[key] !== undefined) {
return cache[key];
}
var value = fn(...args);
cache[key] = value;
return value;
}
}
function paths(rights, downs) {
if (rights === 0 || downs === 0) {
return 1;
}
return paths(rights - 1, downs) + paths(rights, downs - 1);
}
paths = memoize(paths);
console.log(paths(20, 20)); // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment