Skip to content

Instantly share code, notes, and snippets.

@RSNara
Last active July 7, 2019 00:24
Show Gist options
  • Save RSNara/d15e10403ac85ec9c977 to your computer and use it in GitHub Desktop.
Save RSNara/d15e10403ac85ec9c977 to your computer and use it in GitHub Desktop.
An example of using decorators in ES5.
function memoize(object, name, descriptor) {
var fn = descriptor.value;
var memoized = function() {
memoized.cache = memoized.cache || {};
var key = JSON.stringify(arguments);
return memoized.cache[key] = memoized.cache[key]
? memoized.cache[key]
: fn.apply(this, arguments);
}
descriptor.value = memoized;
return descriptor;
}
function decorate(object, name, descriptor, decorator) {
Object.defineProperty(
object, name, (decorator(object, name, descriptor) || descriptor)
);
}
var descriptor = {
value: function(n) {
if (n === 0 || n === 1) return n;
return this.fibonacci(n-1) + this.fibonacci(n-2);
},
enumerable: true,
configurable: true,
writable: true,
};
decorate(Math, 'fibonacci', descriptor, memoize);
// first call
Math.fibonacci(3688) // Infinity
// first call (MacBook Pro)
Math.fibonacci(3689) // RangeError: Maximum call stack size exceeded
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment