odin-default-js-exercises/calculator/calculator.js

54 lines
957 B
JavaScript
Raw Normal View History

const add = function(a, b) {
return a + b;
};
2017-09-20 23:04:46 +00:00
const subtract = function(a, b) {
return a - b;
};
2017-09-20 23:04:46 +00:00
const sum = function(array) {
return array.reduce((total, current) => total + current, 0);
};
2017-09-20 23:04:46 +00:00
const multiply = function(array) {
return array.length
? array.reduce((accumulator, nextItem) => accumulator * nextItem)
: 0;
};
2017-09-20 23:04:46 +00:00
const power = function(a, b) {
return Math.pow(a, b);
};
2017-09-20 23:04:46 +00:00
//alternate solution using Exponentiation opertator
const power = function(a, b) {
return a ** b;
};
const factorial = function(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!
const recursiveFactorial = function(n) {
if (n === 0) {
return 1;
}
return n * recursiveFactorial (n-1);
};
2017-09-20 23:04:46 +00:00
module.exports = {
add,
subtract,
sum,
multiply,
power,
factorial
};