Skip to content

memoize

Subhajit Sahu edited this page Jul 29, 2022 · 3 revisions

Generate result-cached version of a function.


function memoize(x, fr, cache)
// x:     a function
// fr:    resolver ((...args) => unique key) [IDENTITY]
// cache: result cache [Map()]
const xfunction = require('extra-function');


var calls = 0;

function factorialRec(n: number) {
  if (n<=1) return 1;
  return n * factorialRec(n-1);
}

function factorial(n: number) {
  ++calls;
  return factorialRec(n);
}

var fn = xfunction.memoize(factorial);
fn(3);
// → 6
fn(4);
// → 24
fn(5);
// → 120
fn(3);
// → 6
fn(4);
// → 24
fn(5);
// → 120
calls;
// → 3


var calls = 0;

function hypot(x: number, y: number) {
  ++calls;
  return Math.hypot(x, y);
}

function resolver(x: number, y: number) {
  return 4093*y + x;  // a hash
}

var fn = xfunction.memoize(hypot, resolver);
fn(3,  4);
// → 5
fn(6,  8);
// → 10
fn(5, 12);
// → 13
fn(3,  4);
// → 5
fn(6,  8);
// → 10
fn(5, 12);
// → 13
calls;
// → 3


References

Clone this wiki locally