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

51 lines
864 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
};
const sum = function (...args) {
return args.reduce((total, current) => total + current, 0);
2022-02-20 19:07:44 +00:00
};
const multiply = function(...args){
2023-06-07 17:58:54 +00:00
let product = 1;
for (let i = 0; i < args.length; i++) {
product *= args[i];
}
return product;
};
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
};