Skip to content

Instantly share code, notes, and snippets.

@HichamBenjelloun
Last active January 2, 2022 21:38
Show Gist options
  • Save HichamBenjelloun/efb8765d6d486d02f8b9eed36b506487 to your computer and use it in GitHub Desktop.
Save HichamBenjelloun/efb8765d6d486d02f8b9eed36b506487 to your computer and use it in GitHub Desktop.
Memoizing recursive functions
const memoizeFactory = hashFn => fn => {
const memoize = fn => {
const cache = {};
return (...args) => {
const key = hashFn(args);
if (key in cache) {
return cache[key];
}
return cache[key] = fn(...args);
};
};
const newDefinition = `
return memoize => {
const ${fn.name} = memoize(${fn.toString()});
return ${fn.name};
};
`;
return new Function(newDefinition)()(memoize);
};
export default memoizeFactory;
@HichamBenjelloun
Copy link
Author

HichamBenjelloun commented Jul 25, 2020

Je sais, vous pourriez absolument faire quelque chose de ce genre :

const fib = memoize(n => n < 2n ? n : fib(n - 1n) + fib(n - 2n));

Ici, fib fait directement référence à la fonction mémoïsée et ce serait la façon recommandée de faire.

Cela dit, avec memoFactory, vous pourriez importer une fonction récursive non mémoïsée d'un autre package et faire ceci :

const memoize = memoizeFactory(x => x);
const memoFib = memoize(fib);

Cool, n'est-ce pas ? 😄

Voici quelques tests jsperf : https://jsperf.com/memoize-fibonacci

Si vous voulez en savoir plus sur la mémoïsation, vous pouvez lire cet article.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment