odin-default-js-exercises/08_calculator/solution/calculator-solution.js

47 lines
818 B
JavaScript
Raw Normal View History

2022-02-20 19:07:44 +00:00
const add = function (a, b) {
2023-01-21 17:53:41 +00:00
return a + b;
2022-02-20 19:07:44 +00:00
};
const subtract = function (a, b) {
2023-01-21 17:53:41 +00:00
return a - b;
2022-02-20 19:07:44 +00:00
};
2023-07-16 21:06:25 +00:00
const sum = function (array) {
return array.reduce((total, current) => total + current, 0);
2022-02-20 19:07:44 +00:00
};
2023-07-16 21:06:25 +00:00
const multiply = function (array) {
return array.reduce((product, current) => product * current)
};
2022-02-20 19:07:44 +00:00
const power = function (a, b) {
2023-01-21 17:53:41 +00:00
return Math.pow(a, b);
2022-02-20 19:07:44 +00:00
};
const factorial = function (n) {
2023-01-21 17:53:41 +00:00
if (n === 0) return 1;
let product = 1;
for (let i = n; i > 0; i--) {
product *= i;
}
return product;
2022-02-20 19:07:44 +00:00
};
// This is another implementation of Factorial that uses recursion
// THANKS to @ThirtyThreeB!
const recursiveFactorial = function (n) {
2023-01-21 17:53:41 +00:00
if (n === 0) {
return 1;
}
return n * recursiveFactorial(n - 1);
2022-02-20 19:07:44 +00:00
};
module.exports = {
2023-01-21 17:53:41 +00:00
add,
subtract,
sum,
multiply,
power,
factorial,
2022-02-20 19:07:44 +00:00
};