Last active
January 2, 2022 21:38
-
-
Save HichamBenjelloun/efb8765d6d486d02f8b9eed36b506487 to your computer and use it in GitHub Desktop.
Memoizing recursive functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
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
Yes, you can definitely write something like:
Here,
fib
directly references the memoized function and it would be the recommended way to proceed.With
memoFactory
however, you can import another recursive function that has not been memoized yet and do this:Cool, isn't it? 😄
Here are some jsperf tests: https://jsperf.com/memoize-fibonacci
If you want to learn more about memoization, you can read this article.