Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.