Created
November 26, 2018 10:27
-
-
Save jackinf/0d923f46d6c197c7ee4465e11c532b06 to your computer and use it in GitHub Desktop.
JS: Memoization example
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
function memoize(fn) { | |
return function() { | |
const args = Array.prototype.slice.call(arguments); | |
fn.cache = fn.cache || {}; | |
return fn.cache[args] | |
? fn.cache[args] | |
: (fn.cache[args] = fn.apply(this, args)); | |
}; | |
} | |
function sleep(timeout) { | |
return new Promise(resolve => setTimeout(resolve, timeout)); | |
} | |
async function sqrt(num) { | |
await sleep(1000); // fake background worker | |
return Math.sqrt(num); | |
} | |
// No memoization | |
async function app1() { | |
console.log(await sqrt(3)); | |
console.log(await sqrt(3)); | |
console.log(await sqrt(3)); | |
} | |
// Applying memoization | |
async function app2() { | |
const memoizedSqrt = memoize(sqrt); | |
console.log(await memoizedSqrt(9)); | |
console.log(await memoizedSqrt(9)); | |
console.log(await memoizedSqrt(9)); | |
} | |
app1(); | |
app2(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment