Last active
July 5, 2018 09:17
-
-
Save ccnokes/a72cafdf4b7e0788b6994c8b5e02becc to your computer and use it in GitHub Desktop.
Wrap a lodash method in a TS decorator
This file contains hidden or 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
//wrap a fn that returns a function into a decorator | |
function makeFnWrapDecorator(fnWrapper: Function) { | |
return function decoratorWrapper(...args) { | |
return function decorator(target, propertyKey: string, descriptor: PropertyDescriptor) { | |
const fn = descriptor.value; | |
let wrappedFn = fnWrapper.apply(null, [fn, ...args]); | |
return { | |
configurable: true, | |
get() { | |
return wrappedFn; | |
} | |
}; | |
}; | |
}; | |
} | |
/* Test it out */ | |
const memoize = makeFnWrapDecorator(_.memoize) | |
const debounce = makeFnWrapDecorator(_.debounce); | |
class Test { | |
@memoize() | |
add() { | |
console.log('add called'); | |
return 1 + 5; | |
} | |
@debounce(3000, {leading: false, tail: true}) | |
debounced() { | |
console.log('debounce called'); | |
} | |
} | |
const t = new Test(); | |
t.add(); | |
t.add(); | |
t.add(); //should only log "add called" once | |
t.debounced(); //called 3 seconds later | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment