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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Je sais, vous pourriez absolument faire quelque chose de ce genre :
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 :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.