# factorial(n) diffs

## JavaScript performance comparison

Test case created by KLUU4O4

## Preparation code

``````

<script>
Benchmark.prototype.setup = function() {
const iota = n => {
let res = new Array(n)
for (let i = 0; i < n; i++)
res[i] = i
return res
}

const add = (a, b) => a + b
const multiply = (a, b) => a * b
const product = (res, a, i) => res * (i + 1)

const n = [10, 50, 99, 100, 101, 89, 88, 21, 150, 123, 169, 13, 100, 103]
};

</script>
``````

## Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
reduce() / 1 // map()
``````const factorial = n =>
iota(n).map(i => i + 1).reduce(multiply, 1)

n.forEach(factorial)``````
pending…
reduce() / 1b// slice(1)
``````const factorial = n =>
iota(n+1).slice(1).reduce(multiply, 1)

n.forEach(factorial)``````
pending…
reduce() / 1c// filter()
``````const factorial = n =>
iota(n+1).filter(i => i > 0).reduce(multiply, 1)

n.forEach(factorial)``````
pending…
reduce() / 2 // Array.from()
``````const factorial = n =>
Array.from({ length: n }, (v, i) => i + 1).reduce(multiply, 1)

n.forEach(factorial)``````
pending…
while / 3 //
``````const factorial = (n, res = 1) => {
while (n > 0) res *= n--
return res
}

n.forEach(factorial)``````
pending…
recurs. / 0 // arrow
``````const factorial = n =>
n < 2 ? 1 : n * factorial(n - 1)

n.forEach(factorial)``````
pending…
reduce() / 2b// alt.
``````const factorial = n =>
Array.from({ length: n }).reduce(product, 1)

n.forEach(factorial)``````
pending…
reduce() / 2c// alt.
``````const factorial = n =>
Array(n).fill().reduce(product, 1)

n.forEach(factorial)``````
pending…
reduce() / 2d// alt.
``````const factorial = n =>
[...Array(n)].reduce(product, 1)

n.forEach(factorial)``````
pending…
reduce() / 2e// alt.
``````const factorial = n =>
Array.from(Array(n)).reduce(product, 1)

n.forEach(factorial)``````
pending…
reduce() / 1a// w/o map()
``````const factorial = n =>
iota(n).reduce(product, 1)

n.forEach(factorial)``````
pending…
recurs. / 0b// TCO
``````const factorial = n => {
const fact = (n, acc) =>
n < 2 ? acc : fact(n - 1, n * acc)

return fact(n, 1)
}

n.forEach(factorial)``````
pending…
memoize / 4 //
``````const factorial = (() => {
let cache = {}
const fn = n =>
n === 0
? 1
: cache[n]
? cache[n]
: cache[n] = n * fn(n - 1)
return fn
})()

n.forEach(factorial)``````
pending…

You can edit these tests or add even more tests to this page by appending `/edit` to the URL.