3

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)

1
  • Please include all code necessary to understand the question on Stack Overflow itself, rather than on a third-party site. Commented Aug 8, 2016 at 21:59

3 Answers 3

2

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🌹.

Sign up to request clarification or add additional context in comments.

1 Comment

legit! making it an member is a great solution... still I do wish I could have used a decorator to solve this....
2

A simple and elegant solution for have @memoize() decorator:

function memoize() {
    return function (target: any, functionName: string) {
      target[functionName] = _.memoize(target[functionName]);
    };
}

Live example: http://codepen.io/fabien0102/pen/KgPrOy?editors=0012

Comments

2

fabien0102's solution can easily be improved to support getters:

export function memoize() {
  return function (target: any, functionName: string, descriptor: PropertyDescriptor) {
    if (descriptor.get) descriptor.get = _.memoize(descriptor.get, function<T>(this: T):T { return this; });
    else descriptor.value= _.memoize(descriptor.value);
  };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.