Last active
September 28, 2018 10:42
-
-
Save m8r1x/d9fa208e3e1c4753511f403ef1357c27 to your computer and use it in GitHub Desktop.
Function Cache and Async function timer
This file contains 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
function cacheFn(fn) { | |
const cache = new Map(); // need .has, .get, .set methods. | |
return (...args) => { | |
const cacheKey = JSON.stringify(args.reduce((argsObject, arg, index) => { argsObject[index] = arg; return argsObject }, {})); | |
if (cache.has(cacheKey)) { | |
return cache.get(cacheKey); | |
} | |
const computed = fn(...args); | |
cache.set(cacheKey, computed); | |
return computed; | |
}; | |
} | |
function timeFnAsync(fn) { | |
return async (...args) => { | |
console.time("execution time"); | |
const promise = await fn(...args); | |
console.timeEnd("execution time"); | |
return promise; | |
}; | |
} | |
/* | |
* USAGE: | |
* | |
* const api = { | |
* users: (limit, delay=2000) => | |
* new Promise((resolve, reject) => | |
* setTimeout(() => resolve([{id:1}, {id:2}, {id:3}, {id:4}, {id:5}].slice(0, limit)), delay)), | |
* }; | |
* | |
* api.users(3).then(results => console.log(results)) // logs Array with 3 Objects after 2 seconds | |
* | |
* const cachedUsers = cacheFn(api.users) | |
* | |
* cachedUsers(3).then(result => console.log(result)) // Cache miss : logs result after 2 seconds NOTE: this also populates the cache | |
* | |
* cachedUsers(3).then(result => console.log(result)) // Cache hit : logs result immediately | |
* | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment