NietzscheProgrammer NietzscheProgrammer - 4 months ago 8
Javascript Question

Updating operation from sum to subtract or viceversa depending on a given value

I need to sum or subtract the values of an array.

For example:

[1, 5, 10]
should be represented as:
1 + 5 + 10 = 16
.

And
[1, 5, -1, 10, 5]
should be:
1 + 5 - 10 - 5
the
-1
number indicates subtraction or sum depending where the
-1
is. The 1st
-1
will indicate subtraction, the second one
-1
indicates that everything is getting back to a regular sum as everything was in the beginning, the 3rd will be subtraction again, and so on.

Now look how it should be with 2
-1
s:
[1, 5, -1, 10, 5, -1, 5, 5]
, it
should be represented as:
1 + 5 - 10 - 5 + 5 + 5
, got it ?

So, everything should be sum up until the array contains a
-1
so it changes to subraction, if there is another
-1
the operation should change to be a sum. And so on, every time there is a new '-1' the operation changes to the contrary it was before.

I am doing that calculation like this:

function calculate (){

logingValues();
var total = 0;
var shouldSubtract = false;

for (var i = 0; i < arrayOfNumbers.length; i++) {
if (arrayOfNumbers[i] === "") continue;
var currentNumber = parseInt(arrayOfNumbers[i], 10);

if(isNaN(currentNumber)) {
currentNumber = 0;
}

if (currentNumber === -1) {
shouldSubtract = true;
} else {
if (shouldSubtract) {
total -= currentNumber;
shouldSubtract = false;
} else {
total += currentNumber;
}
}
}
caculationEffect(total);
}


And here is the whole code

Any suggestions?

Answer

You could use a variable for the deciding if to add or subtract the actual value.

function sum(array){
    var negative;
    return array.reduce(function (a, b) {
        if (b === -1) {
            negative = !negative;
            return a;
        }
        return negative ? a - b : a + b;
    }, 0);
}

console.log(sum([1, 5, 10]));
console.log(sum([1, 5, -1, 10, 5]));
console.log(sum([1, 5, -1, 10, 5, -1, 5, 5]));