Skip to content

Instantly share code, notes, and snippets.

@elitenomad
Created June 20, 2018 10:28
Show Gist options
  • Save elitenomad/ae9b5def5932cf585b9f2ff1136935bd to your computer and use it in GitHub Desktop.
Save elitenomad/ae9b5def5932cf585b9f2ff1136935bd to your computer and use it in GitHub Desktop.
factorial with Memoization
const factorialRecursiveWithMemoization = (n) => {
const multiplyer = (ender) => {
if(ender == 1){
return ender;
}else{
return (ender * multiplyer(ender - 1))
}
}
return multiplyer(n);
}
const factorialRecursiveMemoization = factorialRecursiveWithMemoization(1);
console.log(`What is factorialRecursiveMemoization ${factorialRecursiveMemoization}`);
@elitenomad
Copy link
Author

elitenomad commented Jun 20, 2018

const factorialWithRecursive = (n) => {
  if(n == 0){
    return n;
  }else{
    return (n * factorialWithRecursive(n - 1));
  }
}

const memoize = (cb) => {
  let cache = {};
	return (n, ...args) => { //[9]
		if (n in cache) {
			console.log('Fetching from cache:', n);
			return cache[n];
		}
		else {
			console.log('Calculating result');
			let result = cb(n); // cb(9)
			cache[n] = result;
			return result;
		}
	};
};

const factorialRecursiveMemoization = memoize(factorialWithRecursive);
console.log(`What is factorialRecursiveMemoization ${factorialRecursiveMemoization(5)}`);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment