A simple way to avoid overcomplicating mathematical operations is to break them
down in the same way we would a mathematical formula.
First let’s look at summing integers.
The sum of integers from 1
to n
can be computed with the formula n*(n+1)/2
.
Now order to compute the sum of integers between (inclusive) two integers,
we can simply take the integer sum of the larger integer and subtract the
integer sum of 1 less than the smaller integer.
function integerSum(n) {
return (n * (n + 1)) / 2;
}
function sumAll(a, b) {
return integerSum(Math.max(a, b)) - integerSum(Math.min(a, b) - 1);
}
Breaking the solution down algebraicly allowed us to write two simpe functions
that did not require creation of any variables to provide the resulting value.
You COULD rewrite the function to perform the operation integerSum
inside of
sumAll
but you would either want to cast to a variable or call Math.max
and
Math.min
twice. I haven’t ran performance tests of the different variations
to say which might be better, but the way I’ve provided is rather efficient.
Your original example code used an array of 2 integers as it’s input, which we
can reproduce by adjusting our sumAll
slightly as follows:
function sumAll(n) {
return integerSum(Math.max(n[0], n[1])) - integerSum(Math.min(n[0], n[1]) - 1);
}
These same functions can be expressed in ES6 syntax as follows:
const integerSum = n => (n * (n + 1)) / 2;
const sumAll = (a, b) => integerSum(Math.max(a, b)) - integerSum(Math.min(a, b) - 1);
Or to allow for an arbitrary number of possible provided arguments:
const integerSum = n => (n * (n + 1)) / 2;
const sumAll = (...n) => integerSum(Math.max(...n)) - integerSum(Math.min(...n) - 1);
Or using your original function signature:
const integerSum = n => (n * (n + 1)) / 2;
const sumAll = (n) => integerSum(Math.max(...n)) - integerSum(Math.min(...n) - 1);