Skip to content

Instantly share code, notes, and snippets.

@thephilip
Last active June 16, 2017 13:27
Show Gist options
  • Save thephilip/5ca17c9e55723094a0c0b460e4aee72f to your computer and use it in GitHub Desktop.
Save thephilip/5ca17c9e55723094a0c0b460e4aee72f to your computer and use it in GitHub Desktop.
/* Function object extension to add memoization
* to any single-argument function.
*/
Function.prototype.memoized = function () {
let key = JSON.stringify(arguments);
this._cache = this._cache || {};
this._cache[key] = this._cache[key] ||
this.apply(this, arguments);
return this._cache[key];
};
Function.prototype.memoize = function () {
let fn = this;
if (fn.lenth === 0 || fn.length > 1) {
return fn;
}
return function () {
return fn.memoized.apply(fn, arguments);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment