Skip to content

Instantly share code, notes, and snippets.

@devinrhode2
Forked from RSNara/decorators.js
Created November 27, 2018 19:26
Show Gist options
  • Save devinrhode2/9669cfd773ff2b9592e94424335c5521 to your computer and use it in GitHub Desktop.
Save devinrhode2/9669cfd773ff2b9592e94424335c5521 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
@devinrhode2
Copy link
Author

  • need to find out where decorator is defined in lodash source

@devinrhode2
Copy link
Author

decorate.js doesn't exist, but memoize.js does, but not very helpful: https://github.com/lodash/lodash/blob/master/memoize.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment