JavaScript Closures calculate sum [duplicate] - javascript

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.

Related

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

How to multiply objects by specified rules? [duplicate]

This question already has answers here:
Javascript: operator overloading
(9 answers)
Closed 4 years ago.
Let's say i want an object that when multiplied with, it multiplies by two and subtracts 1.
The syntax would look like this:
var a = {
on_multiply: function(context){
return context*2-1
}
};
alert(2*a);
This would output 3.
I don't want to write
"a.on_multiply(2)"
Is there a way to do this?
If yes, is it possible to do this with arrays or matrixes also?
The simplest way I can think of to make the above example work is to assign a function named a, and have the context as a parameter of that function:
function a(context) {
return (context * 2) - 1;
}
And if you really wanted a to be a function assigned to a name:
const a = context => 2 * context - 1;
And the above in ES5 syntax:
const a = functipn(context) {
return (context * 2) - 1;
}
Hopefully this helps!

javascript: 'return' is ignored and keeps looping [duplicate]

This question already has answers here:
What does `return` keyword mean inside `forEach` function? [duplicate]
(2 answers)
Short circuit Array.forEach like calling break
(30 answers)
Closed 4 years ago.
function checkMagazine(magazine, note) {
var map = new Map();
var noteAr = note.split(" ");
var magazineAr = magazine.split(" ")
noteAr.forEach((note) => {
if (map.has(note)) {
map.set(note, map.get(note) + 1)
} else {
map.set(note)
}
});
magazineAr.forEach((word) => {
if (!map.has(word)) {
return "No"
}
});
return "Yes"
}
I'm checking to see if each word of a note is contained in the magazine by first hashing the values of the note and checking them in magazineAr. If the note word does not exist in the hash, then I am return "NOing. However, I keep getting a return "YES" in console.
I've watched it in debugger mode and I see it enter the statement where it hits 'return No' but then it just keeps on going with the forEach loop. I've even tried return false but same thing.
A forEach callback ignores the value that's returned - no matter what it is, every item in the array will be called with the forEach. For what you're trying to do, you should probably use every instead, which checks whether all items in the array fulfill the condition:
const hasEveryWord = magazineAr.every(word => map.has(word));
return hasEveryWord
? "Yes"
: "No";

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

Why can't a variable be set to a <number>.toString(), but you can can call toString() on a return value? [duplicate]

This question already has answers here:
Why can't I access a property of an integer with a single dot?
(5 answers)
Closed 6 years ago.
function s(e) {
return e.toString();
}
var a = s(3); // works
var b = 3.toString(); // error
For example, set var a to the return value of s() that returns the first argument.toString(), but you can't set var b to 3.toString()
Javascript is expecting number(s) after the decimal, you can still do this, but you need to put your number in parenthesis:
(3).toString() = "3"

Categories

Resources