common function that accept all argument in javaScript [duplicate] - javascript

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))

Related

JavaScript Closures calculate sum [duplicate]

This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
"add" function that works with different combinations of chaining/arguments
(4 answers)
Puzzle: JS Function that returns itself until there are no arguments
(5 answers)
Variadic curried sum function
(19 answers)
Closed 1 year ago.
I just started learning closures in JavaScript and I'm trying to understand a basic problem.
For example, I'm trying to implement the sum method: sum(1)(4)(5)
const sum = (a) => {
return (b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
}
When I call: console.log(sum(1)(4)(5)()) it works perfect and return 10. However, if I call console.log(sum(1)(4)(5)), it returns [Function (anonymous)]. Why?
Thanks
Every time you call your function like:
sum(1)(10)
you are returning the inner function:
(b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
Because type of b === 'number' and you are returning sum(a+b) that calls
again the function sum and returns again the inner function. Thats why when you finally put the last parenthesis like:
sum(1)(10)()
The inner function will execute and type of b in this case is different from number and will return 'a' that already contains the sum of the values.

How can I use a string name as a function call? If string = 'sum' and function is sum(a, b)? [duplicate]

This question already has answers here:
Get JavaScript function-object from its name as a string?
(9 answers)
Closed 2 years ago.
That's about it. I have a string = "sum" and a function named sum(a,b), how can I substitute my string to call that function;
string = "sum"
function sum(a,b)
So basically to call that function, I would want to execute it like
string(a, b)
I suggest you use dictionary, where you define all existing functions:
const funcs = {
sum: function(a, b) {
},
someStuff: function(r, f) {
}
};
//call it:
funcs["sum"](a, b);
You can simply access your function via indexing with the strings

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.

How can I pass an array as arguments to a function? [duplicate]

This question already has answers here:
Passing an array as a function parameter in JavaScript
(12 answers)
Closed 6 years ago.
if(a == 1){
parameter = ['1','true','a'];
}else{
parameter = ['2','false','b'];
}
function run(a,b,c){
}
How can I pass an array as arguments to the function run? I tried JSON.Stingify but it doesn't work as I'm still seeing the array bracket in my console.log()
You can use javascript apply():
run.apply(this, parameter);
Here are two options.
Call the function directly.
if(a == 1){
run('1', 'true', 'a');
}else{
run('2', 'false', 'b');
}
Or use Function.prototype.apply to call the function with an array as arguments.
if(a == 1){
parameter = ['1','true','a'];
}else{
parameter = ['2','false','b'];
}
run.apply(null, parameter);
Just do it like this:
http://codepen.io/anon/pen/xGaWNr
Code
x = ['2','false','b'];
var run = function (x0,x1,x2) {
document.write (x0+'<br>');
document.write (x1+'<br>');
document.write (x2+'<br>');
}
run(x[0],x[1],x[2]);
Output
2
false
b

Add numbers using inner function - JavaScript [duplicate]

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.

Categories

Resources