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

51 lines
848 B
JavaScript
Raw Normal View History

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