odin-javascript-exercises/calculator/calculator.js
bchalman b030e9a66b
Fix return value of recursive factorial function
While the previous return functioned the same (because it was calling another factorial function), it was not recursive. All credit still to ThirtyThreeB, just thought this might confuse some people and was worth fixing!
2018-08-19 13:02:55 -07:00

46 lines
742 B
JavaScript

function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function sum(array) {
return array.reduce((current, total) => total + current, 0);
}
function multiply(array) {
return array.reduce((current, total) => total * current, 1);
}
function power(a, b) {
return Math.pow(a, b);
}
function factorial(n) {
if (n == 0) return 1;
let product = 1;
for (let i = n; i > 0; i--) {
product *= i;
}
return product;
}
// This is another implementation of Factorial that uses recursion
// THANKS to @ThirtyThreeB!
function recursiveFactorial(n) {
if (n===0){
return 1;
}
return n * recursiveFactorial (n-1);
}
module.exports = {
add,
subtract,
sum,
multiply,
power,
factorial
};