2021-05-09 12:06:18 +00:00
|
|
|
const add = function(a, b) {
|
2021-04-30 10:12:52 +00:00
|
|
|
return a + b;
|
2021-05-10 08:08:31 +00:00
|
|
|
};
|
2017-09-20 23:04:46 +00:00
|
|
|
|
2021-05-09 12:06:18 +00:00
|
|
|
const subtract = function(a, b) {
|
2021-04-30 10:12:52 +00:00
|
|
|
return a - b;
|
2021-05-10 08:08:31 +00:00
|
|
|
};
|
2017-09-20 23:04:46 +00:00
|
|
|
|
2021-05-09 12:06:18 +00:00
|
|
|
const sum = function(array) {
|
2021-04-30 10:12:52 +00:00
|
|
|
return array.reduce((total, current) => total + current, 0);
|
2021-05-10 08:08:31 +00:00
|
|
|
};
|
2017-09-20 23:04:46 +00:00
|
|
|
|
2021-05-09 12:06:18 +00:00
|
|
|
const multiply = function(array) {
|
2021-04-30 10:12:52 +00:00
|
|
|
return array.length
|
|
|
|
? array.reduce((accumulator, nextItem) => accumulator * nextItem)
|
|
|
|
: 0;
|
2021-05-10 08:08:31 +00:00
|
|
|
};
|
2017-09-20 23:04:46 +00:00
|
|
|
|
2022-01-26 20:04:37 +00:00
|
|
|
const power = function(a, b) {
|
2021-04-30 10:12:52 +00:00
|
|
|
return Math.pow(a, b);
|
2021-05-10 08:08:31 +00:00
|
|
|
};
|
2017-09-20 23:04:46 +00:00
|
|
|
|
2022-01-26 21:04:46 +00:00
|
|
|
//alternate solution using the Exponentiation operator
|
2022-01-26 20:04:37 +00:00
|
|
|
const altPower = function(a, b) {
|
2022-01-26 19:15:16 +00:00
|
|
|
return a ** b;
|
|
|
|
};
|
|
|
|
|
2021-05-09 12:06:18 +00:00
|
|
|
const factorial = function(n) {
|
2021-05-10 08:08:31 +00:00
|
|
|
if (n === 0) return 1;
|
2021-04-30 10:12:52 +00:00
|
|
|
let product = 1;
|
|
|
|
for (let i = n; i > 0; i--) {
|
|
|
|
product *= i;
|
|
|
|
}
|
|
|
|
return product;
|
2021-05-10 08:08:31 +00:00
|
|
|
};
|
2021-04-29 09:33:30 +00:00
|
|
|
|
2021-04-30 10:12:52 +00:00
|
|
|
// This is another implementation of Factorial that uses recursion
|
|
|
|
// THANKS to @ThirtyThreeB!
|
2021-05-09 12:06:18 +00:00
|
|
|
const recursiveFactorial = function(n) {
|
2021-05-10 08:08:31 +00:00
|
|
|
if (n === 0) {
|
2021-04-30 10:12:52 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
return n * recursiveFactorial (n-1);
|
2021-05-10 08:08:31 +00:00
|
|
|
};
|
2017-09-20 23:04:46 +00:00
|
|
|
|
|
|
|
module.exports = {
|
2021-04-30 10:12:52 +00:00
|
|
|
add,
|
|
|
|
subtract,
|
|
|
|
sum,
|
|
|
|
multiply,
|
|
|
|
power,
|
|
|
|
factorial
|
|
|
|
};
|