Add numbers using inner function - JavaScript [duplicate] - javascript

This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
Closed 8 years ago.
I am trying to create a function "sum" that adds multiple numbers using an inner function. e.g.
sum(1)(2) will print 3
sum(1)(2)(3) will print 6
sum(1)(2)(3)(4) will print 10 and so on
I wrote the following code which works for sum(1)(2).
function sum(num){
function add (b){
console.log(num+=b);
}
return add;
}
How can I extend this to work with multiple calls to inner function?

This is how I would handle it.
Just a single function that accepts 2 numbers. Adds those 2 numbers and returns the sum.
function sum(num1, num2){
return num1+num2;
}
console.log(sum(11, 10));
http://jsfiddle.net/PpsjJ/
Update: I think this is what you want. A function that accepts an array of numbers, and then adds them all together.
function sumAll(numbers){
var result = 0;
numbers.forEach(function(value, key){
result += value;
});
return result;
}
console.log(sumAll([1,2,3]));
http://jsfiddle.net/PpsjJ/1/

I think what you are looking is summing variable number of arguments. What about this:
function sum() {
var total = 0;
for (var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
alert(total);
}
sum(1,2,3,4,5,6);
Prints: 21
You can call sum with any number of arguments.

Related

Why is the argument passed in to my recursive function not updating its value? [duplicate]

This question already has answers here:
What does x++ in JavaScript do?
(4 answers)
Closed 5 years ago.
I'm just playing around with simple recursion and functions. Nothing too serious, but not doing what I expect:
var recursive = function adder (x) {
x = ++x
if (x < 10) {
console.log('x is now: ' + x)
adder(x)
}
return x
}
console.log(recursive(5))
This completes the loop and runs properly, but am wondering why the 'final' output is '6.' Why don't I get the 'final' value of x after all the recursion is done?
x=++x;
x+=1;
x++;
++x;
You need either the pre increment or the increase by operator, or the postincrement without an reassignment. The post increment retuns first, then increments...
alert((1)++)//1
Some ongoing explanations:
var recursive = function adder (x) {
++x;
if (x < 10) {
console.log('x is now: ' + x)
return adder(x); //lets return our added result
}
return x;//if x=10 lets return 10
}
console.log(recursive(5))//will log 10
It mainly didnt work as expected as primitives are passed by value. So there are actually 5 different x variables in 5 different contexts of adder...
Unlike primitives, objects are passed by reference:
function adder(obj){
obj.x++;
if(obj.x<10){
adder(obj);
}
}
var test={x:1};
adder(test);
console.log(test.x);

common function that accept all argument in javaScript [duplicate]

This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 6 years ago.
often time I have this pattern problem in javascript. I have an add function
function add(a, b){
return a + b;
}
then I can do add(1,2) //3
but what if I want to pass in any length of arguments?
I can't do freely add(1,2,3,4). or add(something,something,something). If I want I have to write another add function that accept 4 and 3 arguments.
I know I can use loop them up by loop but how to pass any number of argument to a function in js?
you can use arguments property .
function add(){
var sum=0;
for (var key in arguments)
sum=sum+arguments[key];
return sum;
}
console.log(add(1,2,3,7));
You can loop over arguments and add values
ES6
function add(){
return Array.from(arguments).reduce((p,c)=>p+= !isNaN(c)? +c : 0, 0)
}
console.log(add(1,2,3,4,5))
console.log(add(1,2,3,'a', 7))
ES5
function add(){
return [].slice.call(arguments).reduce(function(p,c){
p+= !isNaN(c)? +c : 0;
return p;
}, 0)
}
console.log(add(1,2,3,4,5))
console.log(add(1,2,3,'a', 7))

Javascript Higher order functions: Passing a callback function into filter not working

I'm trying to filter out an array's values by those that return true. I have a function called noRepeat which returns true if the given year has no digits repeated, and false otherwise.
I have another function called no_repeats(yearStart, yearEnd) that creates an array of years from start to end. I want to filter out this array by those years that have no digits repeated and I'm not sure why that isn't working. Any ideas? I've included the problem statement as well and in the code I show what my output is versus what it should be.
Write a function, `no_repeats(year_start, year_end)`, which takes a
range of years and outputs those years which do not have any
repeated digits.
You should probably write a helper function, `no_repeat?(year)` which
returns true/false if a single year doesn't have a repeat.
Difficulty: 1/5
function no_repeats(yearStart, yearEnd){
//call no repeats on each year from yearStart to yearEnd and return an array of years that have noRepeat(year) === true
var yearRangeArr = [];
var returnArr = [];
while (yearEnd >= yearStart){
yearRangeArr.push(yearEnd);
yearEnd-=1;
}
yearRangeArr.filter(function(year){
return noRepeat(year);
});
return yearRangeArr;
}
function noRepeat(year){ //works
//create an array pushing each year's digits
// if arr.indexOf(digit) > -1 then the digit already exists, so return false
// else append the digit, and if no digit repeats, return true
year = year.toString();
var repeatArr = [];
for (i = 0; i < year.length; i++){
//console.log(repeatArr);
if (repeatArr.indexOf(year[i]) > -1){ //if the digit exists in arr
return false;
}
else{
repeatArr.push(year[i]);
}
}
return true;
}
//var testArr= [1,2,3,4,2];
//console.log(testArr.indexOf(10));
//console.log(noRepeat(1234));
console.log(no_repeats(1234, 1234)); //== [1234]);
console.log(no_repeats(1123, 1123)); // == []); ANSWER SHOULD BE [], I'M GETTING [1123].
filter() returns new value, it does not mutate the original object. You have to assign returned value to your variable:
yearRangeArr = yearRangeArr.filter(function(year){
return noRepeat(year);
});

event assignment using improper iterator value [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I am attempting to create a closure in a loop in order to set an event listener with my iterator value. However, the value in setCookie is not properly being set. What am I doing wrong here?
obj = document.getElementsByClassName("class");
l = obj.length;
i = 0;
function addEv() {
while (i < l) {
obj[i].addEventListener("click", listener.bind(null, i));
function listener(index) {
setCookie("item", index, 24)
}
i++;
}
}
UPDATED ANSWER
On way to capture iterating values is by using immediately invoked functions to capture the value in a closure.
while (i < l) {
obj[i].addEventListener("click", (function(index) {
return function(ev) {
//setCookie("item", index, 24)
console.log(index)
};
}(i)));
i++;
}
This example will wrap the iterating i as index.

alternative to for loop [duplicate]

This question already has answers here:
How can I convert the "arguments" object to an array in JavaScript?
(21 answers)
Closed 7 years ago.
How do I use .forEach instead of a for loop?
'use strict';
var score = (function(){
function updateScore() {
for(var i = 0; i < arguments.length; i++) {
this.score += arguments[i];
}// I want to use .forEach here instead of for loop.
return this.score;
}
return {
update: updateScore
}
})();
var soccer = {
name: 'Soccer',
score: 0
}
score.update.apply(soccer, [1,2,3])
console.log(soccer.score)
this will log 6.
I tried this
function updateScore() {
arguments.forEach((args, i) => {
this.score += args[i];
};
return this.score;
};
Error log: arguments.forEach is not a function
In modern (ES2015) JavaScript you can use Array.from():
Array.from(arguments).forEach((arg) => {
this.score += arg;
});
You don't need to use array indexing, as the .forEach() function passes each array element to the callback function as the first argument. (It does pass the index as the second argument, but in this case you wouldn't need to use that.)
It's important to note that if the arguments object is passed out of a function (as it would be here), the overall function may be considered ineligible for optimization. That's because the arguments object has some weird properties that make it very hard for the optimizer to know what's going on and whether it's safe to make assumptions about how local variables change. If that's a concern, then the only option is to copy the arguments into a simple array with a for loop.

Categories

Resources