Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active July 5, 2018 09:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/a72cafdf4b7e0788b6994c8b5e02becc to your computer and use it in GitHub Desktop.
Save ccnokes/a72cafdf4b7e0788b6994c8b5e02becc to your computer and use it in GitHub Desktop.
Wrap a lodash method in a TS decorator
//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