Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Simple function */
- const add = (n) => (n + 10);
- const memoize = (fn) => {
- let cache = {};
- return (...args) => {
- let n = args[0];
- if (n in cache) {
- console.log('Getting result from cache.')
- return cache[n];
- } else {
- console.log('Calculating result');
- let result = fn(n);
- cache[n] = result;
- return result;
- }
- }
- }
- const memoizedAdd = memoize(add);
- console.log(memoizedAdd(5));
- console.log(memoizedAdd(6));
- console.log(memoizedAdd(5));
- /* recursive */
- const factorial = memoize(
- (x) => {
- if (x === 0) return 1;
- else return x * factorial(x - 1)
- }
- )
- console.log(factorial(5));
- console.log(factorial(6));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement