Suppose I have a recursive callback such as this (but more complex):
const weightedFactorial = useCallback(n => {
if (n === 0) {
return 1;
}
return weight * n * weightedFactorial(n - 1);
},[weight]);
Is there a way to store previously calculated values, such that if the function is called on a repeated index, it is possible to skip the recursion?
const value1 = weightedFactorial(60)
// Calculate recursively
const value2 = weightedFactorial(30)
// This value should already be known
// and the calculation should be skipped
I've tried to keep a state with known values but I seem to get stuck in a loop, probably because it needs to be a dependency of the callback,
const [knownValues, setKnownValues] = useState([{ n: 0, value: 1 }]);
const weightedFactorial = useCallback(n => {
const known = knownValues.find(known => known.n === n);
if (known?.value) {
return known.value;
}
const newValue = weight * n * weightedFactorial(n - 1);
setKnownValues(knownValues => [...knownValues, { n, value: newValue }]);
return newValue;
},[knownValues, weight]);