https://dev.to/dhilipkmr/understand-how-to-memoize-a-javascript-function-3gal
What is Memoization anyway? The ability to return the previously calculated value without recalculating them, on receiving same set of inputs again is basically what memoization is.
So whenever a Function receives the same set of input arguments it checks in its cache variable if there is a value already exists for it then returns that value or does a recalculation.
It Helps in reducing the computation time. Faster render time
let output = document.querySelector('.output');
const cache = {};
function memoize(method) {
return async function () {
let args = JSON.stringify(arguments);
cache[args] = cache[args] || method.apply(this, arguments);
return cache[args];
}
}
const getUser = async (userId) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
const userData = await response.json();
return userData;
}
const userIds = [1, 1, 2, 2, 3, 4];
userIds.forEach(async userId => {
let memoizedgetUser = memoize(getUser);
const userData = await memoizedgetUser(userId)
output.innerHTML += `user: ${userData.name} <br/><br/>`
})