Skip to content

Instantly share code, notes, and snippets.

@jackinf
Created November 26, 2018 10:27
Show Gist options
  • Save jackinf/0d923f46d6c197c7ee4465e11c532b06 to your computer and use it in GitHub Desktop.
Save jackinf/0d923f46d6c197c7ee4465e11c532b06 to your computer and use it in GitHub Desktop.
JS: Memoization example
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