Last active
September 9, 2018 14:27
-
-
Save ruliarmando/e7bb3c0dab3a6156e3498057f81892be to your computer and use it in GitHub Desktop.
A naive implementation of memoize function in Javascript
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
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