Reputation: 8589
I have to create a new input text every time the user enters an integer and those integers should be add it to an array which at the end the program must sum or subtract depending on the values.
For example, if the array is like this: [1, 5, 10]
the final result is: 16
but if the array goes like this [2, 3, 7, -1, 5]
the final result should be 7
, why? it is because you sum up 2 + 3 + 7
and then subtract 5
.
The main problem I have right now is that there is something wrong with my code which is not doing the final calculation.
A bit of code:
var arrayOfNumbers = [];
var column = 1;
function logingValues (){
var values = $('input[name^=valuesToSum]').map(function(idx, elem) {
newVal = $(elem).val();
if (isNaN(newVal)) {
newVal = 0;
}
return newVal;
}).get();
console.log("Values aquired from inputs " + values);
arrayOfNumbers = values;
console.log("Values inserted on Array " + arrayOfNumbers);
}
function removeElement (id){
$('#' + id ).remove();
console.log("element #" + id + " was eliminated");
}
function iterateOverArray(array){
var oldArray = array;
var newArray = "";
for (var i = 0; i < oldArray.length; i++) {
newArray += " + " + oldArray[i];
}
return newArray;
}
function addElement (whereToPrint){
logingValues();
var newArray = iterateOverArray(arrayOfNumbers);
var printId = "print" + whereToPrint;
console.log(printId);
console.log("we can see the array like this " + arrayOfNumbers);
$('#'+ printId).html(newArray);
console.log('Element was created');
column += 1;
var newInput = // here goes a template
$('.elemPlaceHold').append(newInput);
}
function loadingBar (){
var summingBar = '<div class="rect1"></div><div class="rect2"></div><div class="rect3"></div><div class="rect4"></div><div class="rect5"></div>';
$('.spinner').append(summingBar);
}
function caculationEffect (countTotal){
$('#result').html("");
loadingBar();
setTimeout(function(){
$('.spinner').html("");
$('#result').html(countTotal);
}, 2000);
}
function calculate (){
console.log("is calculating....");
logingValues();
// Variable to hold your total
var countTotal = 0;
// Variable that states how the process start (sum/subtract)
var conditional = true;
var changeCondition;
for(var i = 0; i < arrayOfNumbers.length; i++) {
if(arrayOfNumbers[i] === -1){
changeCondition = conditional ? conditional = false : conditional;
}else{
if(conditional === true){
countTotal += arrayOfNumbers[i];
}else{
countTotal -= arrayOfNumbers[i];
}
}
}
console.log('countTotal', countTotal);
caculationEffect('countTotal', countTotal);
}
Any suggestions?
EDIT
The only thing to take into account is: before doing the calculation, if there is a -1
in the Array, then it should subtract. Otherwise sum!
Upvotes: 1
Views: 3774
Reputation: 2755
There was a few problems here.
caculationEffect
is only supposed to take countTotal
, but you were passing it caculationEffect('countTotal', countTotal)
arrayOfNumbers
like strings, you have to convert them to numbers first.Try using the below code instead:
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 (currentNumber === -1) {
shouldSubtract = true;
} else {
if (shouldSubtract) {
total -= currentNumber;
shouldSubtract = false;
} else {
total += currentNumber;
}
}
}
caculationEffect(total);
Upvotes: 2
Reputation: 10460
You can perform your calculations as follow:
function calculate(array) {
return array.reduce(function(prev, curr, i, arr) {
if(curr === -1) {
arr[i+1] *= -1;
return prev;
}
return prev + curr;
});
}
Demo:
function calculate(array) {
return array.reduce(function(prev, curr, i, arr) {
if(curr === -1) {
arr[i+1] *= -1;
return prev;
}
return prev + curr;
});
}
console.log(calculate([2, 3, 7, -1, 5]));
console.log(calculate([2, 3, 7, -1, 5, -1, 2]));
console.log(calculate([2, 3, 7]));
Upvotes: 1
Reputation: 2046
1) the array is an array of strings so you get concatenation
var values = $('input[name^=valuesToSum]').map(function(idx, elem) {
newVal = $(elem).val();
if (isNaN(newVal)) {
newVal = 0;
}
return parseInt(newVal); // parseInt or parseFloat
}).get();
2) you are passing "countTotal" as the argument [0] instead of the actual value
caculationEffect('countTotal', countTotal);
function caculationEffect (title, countTotal){ // add title argument
$('#result').html("");
loadingBar();
setTimeout(function(){
$('.spinner').html("");
$('#result').html(countTotal);
}, 2000);
}
Upvotes: 1
Reputation: 5528
You need the reset the conditional value after doing the subtraction. So change
if(arrayOfNumbers[i] === -1){
changeCondition = conditional ? conditional = false : conditional;
}else{
if(conditional === true){
countTotal += arrayOfNumbers[i];
}else{
countTotal -= arrayOfNumbers[i];
}
}
to
if(arrayOfNumbers[i] === -1){
changeCondition = conditional ? conditional = false : conditional;
}else{
if(conditional === true){
countTotal += arrayOfNumbers[i];
}else{
countTotal -= arrayOfNumbers[i];
conditional = true;
}
}
Upvotes: 1
Reputation: 12959
Try it :
<html>
<head>
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<script>
var arr = [2, 3, 7, -1, 5];
function calculate(arr) {
total = 0;
if(arr.length > 0) {
var index = arr.indexOf(-1);
if (index === -1){
for(var i = 0;i <arr.length;i++)
total += arr[i];
}
else {
for(var i=0 ; i<arr.length;i++) {
if(i===index)
continue;
if(i < index)
total+=arr[i];
else
total-=arr[i];
}
}
}
return total;
}
alert (calculate(arr));
</script>
</body>
</html>
Upvotes: 1
Reputation: 3690
The solution is quite simple, if you do a simple console.log(arrayOfNumbers);
, you will notice that your values are stored as strings .
Example of the log :
["3", "4"]
Since you use the === operator, JavaScript also compares the value's types. Indeed, "-1" === -1 returns false. This is the reason why you're never reaching your "changeCondition" code.
Either use the parseInt() function to convert your "string" to the number and your problem will be fixed.
Upvotes: 1