Created
March 9, 2020 08:58
-
-
Save iankit3/53c068cc1d8293c87be4e581ce4cd4eb to your computer and use it in GitHub Desktop.
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
const memoizedGetSomeData = memoize(getSomeMoreData); | |
function getSomeData(foo, callback) { | |
setTimeout(() => { | |
callback('', foo + 1); | |
},100) | |
} | |
function getSomeMoreData(foo, bar, callback) { | |
setTimeout(() => { | |
callback('', foo + bar + 1); | |
},100) | |
} | |
getSomeData('a', (error, response) => { | |
//slow | |
getSomeData('a', (error2, response2) => { | |
//slow | |
}) | |
}) | |
// memoizedGetSomeData('a', (error, response) => { | |
// //slow | |
// console.log(response); | |
// memoizedGetSomeData('a', (error2, response2) => { | |
// //fast | |
// console.log(response2); | |
// }) | |
// }) | |
memoizedGetSomeData('a', {a:"b"}, (error, response) => { | |
//slow | |
console.log(response); | |
memoizedGetSomeData('a', {a:"b"}, (error2, response2) => { | |
//fast | |
console.log(response2); | |
}) | |
}) | |
function memoize(fn){ | |
var map = {}; | |
return function(){ | |
var args = [...arguments] | |
var callB = args.pop(); | |
var arg = args.map(e => JSON.stringify(e)).join(":"); | |
console.log(arg); | |
if(arg in map){ | |
console.log('cache hit'); | |
callB("", map[arg]); | |
}else{ | |
var callBack = (err, out) => { | |
map[arg] = out; | |
callB(err, out); | |
} | |
fn.apply(this,[...args, callBack]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment