Instead of doing it recursively, I took the solution from @Amin Jafari which uses reduce()
. This function is quicker than the recursive solution.
First we generate an array. We do so by using Array(n + 1)
. n
is the factorial so e.g. for 6!
our n
would be 6
. We get the indices with keys()
but Array()
by itself only returns a truly empty array and keys()
only returns an iterator. So we spread it and put the result of that into a new array. Thus, we have e.g. [0,1,2,3,4,5,6]
(for n + 1
with n = 6
). We exclude the 0 with slice(1)
.
Afterwards we finally apply reduce
. Reduce iterates over all elements, applies a function while keeping track of an accumulator. Our accumulator here is the current product. So what happens is that 1 * 2
gets calculated and the result saved in a
, our accumulator. Then we multiply a
with the next value, so 2 * 2*
and this happens until we went through our whole self generated array.
This function based on reduce
we can then use to transform each value in our original array with map()
.
const factorial = n => [...Array(n+1).keys()].slice(1).reduce((a,c) => a * c),
data = [2, 4, 5];
let res = data.map(v => factorial(v));
console.log(res);