mathjs/lib/util/function.js
2015-01-06 22:04:56 +01:00

27 lines
666 B
JavaScript

// function utils
/*
* Memoize a given function by caching the computed result.
* Very limited, supports only functions with one argument, and only primitive
* values as argument.
*
* @param {function} fn The function to be memoized. Must be a pure function.
* @return {function} Returns the memoized function
*/
exports.memoize = function( fn ) {
if (fn.length === 1) {
function memoize( arg ){
if (!(arg in memoize.cache)) {
return memoize.cache[arg] = fn(arg);
}
return memoize.cache[arg];
}
memoize.cache = {};
return memoize;
}
else {
throw new Error('Function must have one argument');
}
};