keslert's Fibonacci example is a good one, here's one more for your understanding using edit distance as an example.
// Map<string, Map<string, number>>
const cache = new Map();
// a: string, b: string
function editDistance(a, b) {
if (a.length === 0) {
return b.length;
}
if (b.length === 0) {
return a.length;
}
let res = cache.getMap(a).get(b);
if (res !== undefined) {
return res;
}
res = Math.min(
editDistance(pop(a), pop(b)) + (last(a) === last(b) ? 1 : 0)
, editDistance(pop(a), b) + 1
, editDistance(a, pop(b)) + 1
);
cache.getMap(a).set(b, res);
return res;
}
It is worth to mention that for some cases, doing the computation directly is less costly than looking up the memory (cache). For example basic logical operation or a few step math.
To determine the exact case in detail, you need to know the mechanism used by the cache (the data structure, complexity of operation, even the medium of storage (i.e. are you using fast RAM or swapped to slow harddisk?)) which is implementation dependent on the browser / JavaScript engine.
source: https://github.com/beenotung/programming-class/blob/3f678ac48511d829149fb06c139e53cc2680ae82/edit-distance/edit-distance.ts
-- edit 2018 Mar 06, 13:56
In the example, the call to pop/1 function can also be cached as well.