memoization javascript
// a simple pure function to get a value adding 10
const add = (n) => (n + 10);
console.log('Simple call', add(3));
// a simple memoize function that takes in a function
// and returns a memoized function
const memoize = (fn) => {
let cache = {};
return (...args) => {
let n = args[0]; // just taking one argument here
if (n in cache) {
console.log('Fetching from cache');
return cache[n];
}
else {
console.log('Calculating result');
let result = fn(n);
cache[n] = result;
return result;
}
}
}
// creating a memoized function for the 'add' pure function
const memoizedAdd = memoize(add);
console.log(memoizedAdd(3)); // calculated
console.log(memoizedAdd(3)); // cached
console.log(memoizedAdd(4)); // calculated
console.log(memoizedAdd(4)); // cached
Also in JavaScript:
- javascript substring messes emoji
- group by in javascript
- jquery select specific radio button by value
- how to create a server in node js
- memoization javascript
- angular router navigate
- next js create store
- how to code a minecraft json file mod
- reactnode prop-types
- js unique using set
- js create object url base64 pdf binary
- input text react 2020
- jsconfig for default vue
- how to add carousel in javascript
- define a while loop in node js
- es6 array sum javascript
- react native side drawer
- sql server import json
- iterate over enum angular ngfor
- set element at index javascript array and create new array
- jquery on body click
- autoformat mobile number (xxx) xxx-xxx codepen
- find year javascript
- promise catch