-
-
Save devinrhode2/9669cfd773ff2b9592e94424335c5521 to your computer and use it in GitHub Desktop.
An example of using decorators in ES5.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
devinrhode2
commented
Nov 29, 2018
- need to find out where decorator is defined in lodash source
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