I am looking for the best way of implementing an optimization for very expensive method that takes multiple parameters and returns an Observable. Is there an elegant way of doing it?
What I am looking for is prettier version of this:
class Example {
constructor(
private databaseService: DatabaseService,
private someService: SomeService)
expensive(param1: string, param2: string) : Observable<string> {
if (isMemoraized(param1,param2) {
return Observable.create(observer=>
observer.next(memorizedValue(param1, param2));
observer.complete();
} else {
return Observable.create(observer=>{
Observable.forkJoin([
this.databaseService.getValue(param1, param2),
this.someService.fetchDataFromServer(param2)].subscribe(
results => {
let result = results[0] + ' ' + results[1];
memorizeValue([param1,param2], result);
observer.next(result);
observer.complete();
});
});
}
}
}
Any help appreciated!
You can create a decorator to memoize the results in run-time for every decorated function:
Usage:
Warning! Decorators are stage 2 proposal of js! Don't use decorators without transpiling your code (Typescript supports it completely)
If you are not willing to use any library and write your own code. I can refactor your code to this :
You could use
localStorage
to keep the results of your expensive operation, indexed by a hash of the two parameters. My solution below also implements expiration to avoid using stale results.There are a number of memoization packages available on NPM. For TypeScript, I'd recommend typescript-memoize, which will provide you with a decorator you can use to memoize your methods.
For example: