I'm trying to create a function that performs Sigma notation calculations in JavaScript. (If you don't know Sigma notation, it will be clear what I'm trying to do below.) My goal is to make a function that can be written as easily as Sigma notation and return the solution that the Sigma notation would calculate. Ideally, I would like calls to the function to only have to provide the starting value, ending value, and the calculation to be performed on each number in the set of numbers before summing them as arguments.
For example,
thisIsMySigmaNotationFunction(1, 4, 2i+1)
would return:
(2(1)+1) + (2(2)+1) + (2(3)+1) + (2(4)+1) = 24
Here is the code I created so far, which works, but I have to create a separate function to use as the 2i+1 argument. I'm wondering if there is a way to avoid this and call the function as above since 2i+1 might need to change to i/(i+1) or other calculations in the future and it would be great to not have to create a separate function to insert as an argument each time.
function sigmaCalculation(start, end, whatToSum){
var sum = 0;
for (var i = start; i <= end; i++){
sum += whatToSum(i);
};
console.log(sum);
}
function calculationToSum(this1){
return 2*this1+1;
}
If it helps at all, you don't need to make named functions for every time you call this, you can use anonymous functions:
sigmaCalculation(1, 4, function(x) { return 2 * x + 1; });
Which can be pretty compact.
Now if you want to do i/(i+1), you just change your call to:
sigmaCalculation(1, 4, function(x) { return x / (x + 1); });
Arrow functions now make this less annoying.
function sigma(start, end, modifier) {
const length = end - start + 1;
const map = (v, k) => modifier ? modifier(k + start) : k + start;
const sum = (a, b) => a + b;
return Array.from({ length }, map).reduce(sum);
}
sigma(3, 5); // 12
sigma(3, 5, i => i+2); // 18
sigma(3, 5, i => i*2); // 24
sigma(3, 5, i => i/(i+1)); // 2.3833333333333333
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With