Skip to content

Instantly share code, notes, and snippets.

@ruliarmando
Last active September 9, 2018 14:27
Show Gist options
  • Save ruliarmando/e7bb3c0dab3a6156e3498057f81892be to your computer and use it in GitHub Desktop.
Save ruliarmando/e7bb3c0dab3a6156e3498057f81892be to your computer and use it in GitHub Desktop.
A naive implementation of memoize function in Javascript
const memoize = function(f) {
let cache = {};
return function(...args) {
const arg_str = JSON.stringify(args);
cache[arg_str] = cache[arg_str] || f.apply(f, args);
return cache[arg_str];
}
}
const squareNumber = memoize(function(x) {
return x * x;
});
console.log(squareNumber(4)); // 16 hasil didapatkan dari menjalankan fungsi
console.log(squareNumber(4)); // 16 hasil didapatkan dari cache
console.log(squareNumber(4)); // 16 hasil didapatkan dari cache
console.log(squareNumber(16)); // 256 hasil didapatkan dari menjalankan fungsi
console.log(squareNumber(16)); // 256 hasil didapatkan dari cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment