ThinkBonobo ThinkBonobo - 4 months ago 33
TypeScript Question

lodash's _.memoize with typescript methods

Does anyone have any experience incorporating lodash's memoize function with a typescript method?

I know typescript supports decorators but I've been having a bit of trouble understanding them.

I created an easy test code to modify with lodash wired to make explaining the solution easier:

https://codepen.io/thinkbonobo/pen/XKyaKY?editors=0010

I'd like to memoize run so that it returns the answer without the forced

wait
. If it is successfully memoized it will return "
MEMOIZED!!! :)
"

run() {
return this.doSomeProcessing();
}


(N.B., I would suggest while coding to comment out the wait function so it doesn't give the synchronous lag from it as the program tries to run)

Answer

You can easily memoize run with the once function https://lodash.com/docs#once:

   run = _.once(() => {
     return this.doSomeProcessing();
   });

Of course this makes it a member instead of a method but that's okay