functions-memoize
by shan10213223
JavaScript
var _ = {};
// _.memoize(func)
// Memoizes a given function by caching the computed result.
// Useful for speeding up slow-running computations.
// You may assume that the memoized function takes only one argument
// and that it is a primitive. Memoize should return a function that when called,
// will check if it has already computed the result for the given argument
// and return that value instead of recomputing it.
_.memoize = function (func) {
const memoizedFunc = function (input) {
// check cache before calling func
let result;
if (memoizedFunc.cache[input] !== undefined) {
result = memoizedFunc.cache[input];
} else {
result = func(input);
memoizedFunc.cache[input] = result;
}
return result;
};
memoizedFunc.cache = {};
return memoizedFunc;
};
// tests
var fibonacci = _.memoize(function(n) {
return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
});
console.log(fibonacci(4));
console.log(fibonacci.cache);
console.log(fibonacci(4));
// process
// https://medium.com/northcoders/improve-your-problem-solving-skills-implementing-underscores-memoize-part-i-eef67ab57d40
// define a complex function
function square (n) {
console.log('calling square with ', n);
return n * n;
}
let memoizeSqre = _.memoize(square);
console.log(memoizeSqre(3));
console.log(memoizeSqre.cache);
console.log(memoizeSqre(3));
/*
// define a place to store computed results
const cache = {};
function memoizeSqre (n) {
let result;
if (cache[n] !== undefined) {
result = cache[n];
} else {
result = square(n);
cache[n] = result;
}
return result;
}
console.log(memoizeSqre(2));
console.log(cache);
console.log(memoizeSqre(2));
*/