mirror of
https://github.com/josdejong/mathjs.git
synced 2026-01-25 15:07:57 +00:00
27 lines
666 B
JavaScript
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');
|
|
}
|
|
};
|