Skip to content

Instantly share code, notes, and snippets.

@arnonate
Created September 18, 2020 19:30
Show Gist options
  • Save arnonate/bca1abfd9a8cdabf1e0829c562a8f97a to your computer and use it in GitHub Desktop.
Save arnonate/bca1abfd9a8cdabf1e0829c562a8f97a to your computer and use it in GitHub Desktop.
// Task 1: Without peeking, write your own recursive factorial method
// Task 2: Use your memo function from the previous exercise to memoize your factorial method
const memoize = cb => {
const cache = {};
return (...args) => {
let n = args[0];
if (n in cache) {
console.log("In CACHE!!");
return cache[n];
}
let result = cb(n);
cache[n] = result;
return cache[n];
};
};
const factorial = memoize(x => {
if (x === 0) {
return 1;
} else {
return x * factorial(x - 1);
}
});
console.log(factorial(100));
console.log(factorial(5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment