Created
November 7, 2016 21:42
-
-
Save zachallaun/5a1231623318de307f14a8cd0b218a02 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
// 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