Last active
August 29, 2015 14:21
-
-
Save calebrash/f8bc04d9099e4ddee224 to your computer and use it in GitHub Desktop.
JS cache decorator function
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
/** | |
* Cacheable decorator function. | |
* @returns cacheable function. Results will be cached based on first argument. | |
**/ | |
let cacheable = function (f) { | |
var __ = {}; | |
return function () { | |
if (__[arguments[0]]) { | |
return __[arguments[0]]; | |
} else { | |
__[arguments[0]] = f.apply(null, arguments); | |
return __[arguments[0]]; | |
} | |
}; | |
}; |
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
// example 1: not cached | |
let fib = function (n) { | |
if (n === 0) { | |
return 0; | |
} else if (n === 1) { | |
return 1; | |
} else { | |
return fib(n-1) + fib(n-2); | |
} | |
}; | |
// example 2: cached | |
let fib2 = cacheable(function (n) { | |
if (n === 0) { | |
return 0; | |
} else if (n === 1) { | |
return 1; | |
} else { | |
return fib2(n-1) + fib2(n-2); | |
} | |
}); | |
// results, times using console.time('...'); | |
var n = 45; | |
fib(n); // 15689.771ms | |
fib2(n); // 0.090ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment