Last active
January 22, 2016 17:11
-
-
Save vintharas/9bfb84ef68aa9e59a5b5 to your computer and use it in GitHub Desktop.
Memoize using a promise (angular $q)
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
/* | |
* | |
* Memoizes call to a service using a promise | |
* | |
*/ | |
function memoizeWithPromise(getFn) { | |
let memoizedCalls = new Map(); | |
return function(...args) { | |
let serializedArgs = JSON.stringify(args); | |
if (memoizedCalls.has(serializedArgs)) { | |
return memoizedCalls.get(serializedArgs); | |
} else { | |
let promise = getFn(...args); | |
memoizedCalls.set(serializedArgs, promise); | |
return promise; | |
// also | |
// let promise = $q.when(getFn(...args)); | |
// memoizedCalls.set(serializedArgs, promise); | |
// return promise; | |
// http://www.bennadel.com/blog/2735-q-when-is-the-missing-q-resolve-method-in-angularjs.htm | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Got code review from the reddits! Yey! ๐ ๐ https://www.reddit.com/r/javascript/comments/425tv2/would_you_mind_codereviewing_this_memoize/