Getting the total of multiple functions outputs in Javascript, node.js - javascript

I have this function called numFunc(), which produces a numeric output.
I want to run this function 5 times and get the sum of all 5 outputs.
Here's what I've tried
function total(){
for (itr=1; itr<=5; itr++) //run the function 5 times
{
var numF = numFunc(); //store the output from the function in a variable
var sum = sum+numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();
But, what I get is the following output
3
3
3
3
3
NaN
What I want is the sum as a single value. How do I achieve this?

You need to declare your variabble outside of the loop and set it to a number value otherwise you are adding an undefined to an integer. Thanks #jfriend00 for the clarification
function total(){
var sum = 0;
for (itr=1; itr<=5; itr++) //run the function 5 times
{
var numF = numFunc(); //store the output from the function in a variable
sum = sum + numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();

In the statement:
var sum = sum + numF;
You are trying to add something that does not yet exist, because you just declared it there with the var
With your statement, you should be declaring the vars above the loop:
function total(){
// declaring the variables before you use them.
// I will set them to 0 so I know they're supposed to be numbers, and 0 wont affect the outcome of the function
var numF = 0;
var sum = 0;
for (itr=1; itr<=5; itr++) //run the function 5 times
{
numF = numFunc(); //store the output from the function in a variable
sum = sum+numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();

What about trying an array, and then adding that array values externally after the function fires like this?
EDIT: Used the repl.it code editor to test this theory out. I had to change the code a bit but remained under the same premise. Used separate the functions and then fed the array builder function into the calculator function to properly calculate the array variables. Repl link here: (https://repl.it/B128/1)
function numFunc(){
return 3;
};
function total(){
var toBeSummed = []; //set up an array to put your sum variables into as a more versatile variable type to perform this in.
for (var itr=0; itr<5; itr++){ //runs the function 5 times
var numF = numFunc(); //store the output from the function
var arrayItr = itr; //uses "itr" variable to iterate a 0 based index 5 times
toBeSummed[arrayItr] = numF; //for each arrayItr 0-5 makes the array value equal to the numF value.
};
return toBeSummed;
};
var sum = 0;
function counter(totals){
for(sums in totals){ //iterates the x array elements(5 in this case)
sum = sum + totals[sums]; // Adds the current value of sum, plus the values at each existing array point(at this point values in array index 0-5)
//console.log(sum); //Should now log the correct set of sums "browser"
};
console.log(sum);
};
counter(total());

Thank you all for your help.
I think I found the issue. The original numFunc() function seemed to have a console.log() statement that's why I kept on getting the list of 3's all the time, replacing that with a return resolved that.
And as you guys suggested declaring the sum variable outside the loop prevented the display of 'NaN'

Related

Anonymous Function prints as string

In Javascript, I wanted to calculate total of two variables received from textbox, let us say txtBoxA and txtBoxB. The value gets calculated in an anonymous function and is stored in a variable total. Please take a look at the following code to see how it is calculated:
var total = function () {
var total = parseFloat(txtbox[1].value) + parseFloat(txtbox[2].value);
if (total == NaN) return 0;
else return total;
};
alert(total);
but unfortunately, the anonymous function itself is printed as it is as shown in the image below.
alert(total);
You are just printing the function variable. If you want to execute it, you have to add (), so that it calls.
alert(total());
And that is not an anonymous function. Just a function declaration and assigning to a variable.

calculating sum of values after combining results of multiple AJAX calls.

I am trying to write a JS function which calculates the sum of all visible rows in a column in a table.
The way the values in the column is filled is by making multiple ajax calls (50 rows at a time).
I am trying to keep track of no of requests sent and when I receive all responses back calculate the sum.
function onClickofCalculateButton() {
var noOfRequestsSent = 0;
var sum = 0;
var sucCallback = function(response) {
updateColumn(response, noOfRequestsSent, sum);
};
//Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}
in my updateColumn function()
function updateColumn(response, noOfRequestsSent, sum) {
noOfRequestsSent--;
//Do some logic to retrieve value of each row and add it to sum
if(noOfRequestsSent == 0) {
alert(sum);
}
}
However what is happening is the value of noOfRequestsSent is always equal to the actual number of requestssent even after subtracting it in updateColumn function. So it never reaches the condition where noOfRequestsSent == 0 and neither does the sum get added onto the previous value.
I guess I have to pass some object reference or something like pointers in C but I am unable to figure out how to do in JS.
You could try like this. Since you want to send variable as reference. In this way you can avoid global variables.
function onClickofCalculateButton() {
var noOfRequests = {
sent:0
};
var sum = 0;
var sucCallback = function(response) {
updateColumn(response, noOfRequests, sum);
};
//Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}
function updateColumn(response, noOfRequestsSent, sum) {
noOfRequests.sent--;
//Do some logic to retrieve value of each row and add it to sum
if(noOfRequests.sent == 0) {
alert(sum);
}
}

What am I doing wrong with this addition code?

var addition=function(num){
var sumSoFar=0;
for(var i=1;i<=num;i++)
{
sumSoFar+=num[i];
return sumSoFar;
}
};
console.log(addition(5));
I wrote this with a while loop a little bit ago. It supposed to take a random (num) and return the sum of all numbers from 1 to (num) Im just not figuring out what im doing wrong with the for loop
inside the for loop you are returning he sum, so you just return 1!
do
var addition=function(num){
var sumSoFar=0;
for(var i=1;i<=num;i++)
{
sumSoFar+=i;
}
return sumSoFar;
};
console.log(addition(5));
also if you just need the sum of i from 1 to n do:
var addition=function(num){
return (1+num) * num / 2;
};
and read on Arithmetic progression
Your return is inside the for loop - it should be outside.
You've put a return statement in the middle of the loop. That will cause the function to return on the first pass through there.
If num is a number, then num[i] doesn't mean anything. You just need to add i.
Do u want to do this:
var addition=function(num){
var sumSoFar=0;
for(var i=1;i<=num;i++)
{
sumSoFar+=i;//will add the loop varible to get sum
}
return sumSoFar;//also function can return a value only once and not in a loop
};

I'm having trouble writing a recursive function in JavaScript - it doesn't seem to "fall back" to the lesser depth correctly

var diceToRoll = [2,2];
var diceRolled = new Array();
function recurse(diceToRoll, diceRolled) {
roll = diceToRoll[0]
diceLeftToRoll = diceToRoll;
diceLeftToRoll.shift();
for(loop=1; loop<(roll+1); loop++) {
result = diceRolled;
result.push(loop);
if(diceLeftToRoll.length == 0) {
console.log(result);
result.pop();
} else {
recurse(diceLeftToRoll, result);
}
}
}
recurse(diceToRoll, diceRolled);
I'm trying to write a recursive function which prints the possible results of any number of dice. For example, a dd100 (diceToRoll = [6, 10, 10, 100])(diceToRoll = [6, 6, 6, 6, 6]) etc. In the example I have used the simplest case(or two 2-sided dice).
I expected the results to be [1,1], [1,2], [2,1], [2,2] however it only logs [1,1], [1,2]. This is the same with any number or type of dice - only the deepest level of recursion works correctly.
I figure I'm missing something obvious in the logic of it / or misunderstanding variable scope in JavaScript, but I'm just really struggling to get my head around it.
Edit 1 (To make explanation of program's purpose clearer)
The programs purpose is to list all possible values on any number of dice. So a dice 6 implies the range of values 1..6. Likewise, a two-sided dice, 2, implies the range of values 1..2. So for two two-sided dice in the example (diceToRoll[2,2]) the possible values are 1,1 1,2 2,1 and 2,2 - which is what should be returned.
There are several issues with your code:
Use var keyword in order to define local variables.
Assigning array to another variable not copies its content, just reference to the same array. Use Array.slice() if you want to clone array.
Here is a fixed function:
var diceToRoll = [2,2],
diceRolled = [];
function recurse(diceToRoll, diceRolled) {
var roll = diceToRoll[0],
diceLeftToRoll = diceToRoll.slice(1),
loop,
result;
for(loop=1; loop<=roll; loop++) {
result = diceRolled.slice(0);
result.push(loop);
if(diceLeftToRoll.length === 0) {
console.log(result);
result.pop();
} else {
recurse(diceLeftToRoll, result);
}
}
}
recurse(diceToRoll, diceRolled);
NOTE
diceToRoll = diceToRoll.slice(1)
is equivalent to
diceToRoll = diceToRoll.slice(0);
diceToRoll.shift();
Fiddle here: http://jsbin.com/isebef/1/edit
You must declare "roll" (and other local variables) with var.
function recurse(diceToRoll, diceRolled) {
var roll = diceToRoll[0]
var diceLeftToRoll = diceToRoll;
diceLeftToRoll.shift();
for(var loop=1; loop<(roll+1); loop++) {
var result = diceRolled;
result.push(loop);
if(diceLeftToRoll.length == 0) {
console.log(result);
result.pop();
} else {
recurse(diceLeftToRoll, result);
}
}
}
Without var, "roll" and "loop" are global.
I'm not sure what the point of "result" is; it's just a reference to the "diceRolled" array, so I'm not sure why you wouldn't just use that.
edit — I'm not sure exactly what your code is trying to do here, but another significant problem is this:
var diceLeftToRoll = diceToRoll;
diceLeftToRoll.shift();
When you make an assignment like that of a value that's a reference to an array, you do not make a copy of the array. Thus both variables refer to the same array object, and the first element will be removed from it. If you instead make "diceLeftToRoll" a copy of the other array, then things work differently:
var diceLeftToRoll = diceToRoll.slice(1); // copy all but 1st element
I don't think the whole thing will work, however, because I now think that the "result" variable was an attempt to do something similar.
edit again Here is an alternative version that returns results in a list. This one avoids making copies except for the final entries added to the result.
function allRolls( dice ) {
var list = [], rolled = [];
function roll( dn ) {
var dp = rolled.length;
for (var dv = 1; dv <= dice[dn]; ++dv) {
rolled[dp] = dv;
if (dn < dice.length - 1)
roll(dn + 1)
else
list.push(rolled.slice(0));
}
rolled.length = dp;
}
if (dice.length) roll(0);
return list;
}
allRolls([3, 3, 3]);
The function involves an inner function that does all the work. It's passed the index in the "dice" list of a dice to roll; initially, that's 0.
The function keeps track of two other lists: the accumulated possible rolls, and an array representing the "rolled so far" for use by the recursive inner function.
At each recursive level, the function iterates through the faces of the current dice (that is, dice[dn]). Each iteration places that dice value in a slot at the end of the "rolled" array; the same slot is used for each iteration. Now, if the loop notices that "dn" represents the last dice in the list, then it makes a copy of the "rolled" array and adds it to the result list. If not, then it makes a recursive call, passing the next dice index down.
The outer function then just checks to see if there are any dice to roll, and rolls them if so. It returns the accumulated list.

how to create a loop in a function with another function?

I'm new to Java and I'm doing a uni course. I've been asked to design three functions.I have to find the difference between each adjacent numbers in an array, another to total the array and the last one to calculate the difference using the other functions then write a programme. I'm totally lost on the last function and my tutor has gone away on hols. Here is the code I have done so far. I don't want people doing the code for me but if anyone can advice me what I need to do I would appreciate your advice. I'm not sure how to loop the difference function into the array and store it into the new array I have made. If anyone could explain where I am going wrong I would love to hear from you!
var numberArray = [10,9,3,12];
// function difference will find the highest value of the two numbers,find the difference between them and return the value.
function difference(firstNumber, secondNumber)
{
if (firstNumber > secondNumber)
{
return (firstNumber - secondNumber);
}
else
{
return (secondNumber - firstNumber);
}
}
// function sum will add the total numbers in the array and return the sum of numbers.
function sum(numberArray)
{
numberTotal = 0
for (var total = 0; total < numberArray.length; total = total + 1)
{
numberTotal = numberTotal + numberArray[total]
}
{
return numberTotal
}
/*code the process that calculates a new array containing the differences between all the pairs
of adjacent numbers, using the difference() function you have already written.
This function should be named calculateDifferences() and should accept an array numberArray.
The function should first create a new empty array of the same size as numberArray
It should then calculate the differences between the pairs of adjacent numbers,
using the difference() function, and store them in the new array. Finally, the function should return the new array.
The calculation of the differences should be done in a loop, at each step finding the difference between each
array element and the next one along in the array, all except for the last difference,
which must be dealt with as a special case, because after the last element we have to wrap round to the start again.
So the final difference is between the last and first elements in the array.*/
function calculateDifferences()
var createArray = new Array (numberArray.length);
{
createArray = 0;
for (var c = 0; c < numberArray.length; c = c + 1)
{
createArray = difference(numberArray[c]);
}
{
return createArray
}
}
your implementation of function "calculateDifferences" is not correct.
this function should look like this:
function calculateDifferences()
{
var createArray = new Array (numberArray.length);
for (var c = 0; c < numberArray.length - 1 ; c = c + 1)
{
/*
because of the function "difference" has two parameters (firstNumber, secondNumber) in its declaration, we should give two arguments. (that are adjacent elements in array)
*/
createArray[c] = difference(numberArray[c],numberArray[c+1]);
}
/ *
calculating difference of first and last element of array and
assign it to returning array's last element.
*/
createArray[numberArray.length - 1] = difference(numberArray[0],numberArray[numberArray.length - 1]);
return createArray;
}
You should index createArray the same way you already do with numberArray[c].

Categories

Resources