Multiply function with 1 argument only [duplicate] - javascript

This question already has answers here:
What is 'Currying'?
(23 answers)
Closed 4 years ago.
I have a javascript coding exercise to do which has got me a bit stuck (I'm only just starting javascript).
The exercise is as follows:
Write a function multiply(a) that returns a function capable of multiplying by a. Call this function with b as a parameter.
So far I have the main skeleton (not difficult):
function multiply(a) {
return //Stuck here
}
I'm not sure if the question is to call multiply(b) and have it give us the result of a*b or something else...
I tried writing a function directly after the return statement but this just printed out the function name.
function multiply(a) {
return function f { return a * b } //Here I assume b is a variable defined somewhere
}
Thanks in advance!

You could take a closure over the variable and return a function for the multiplication for the multiplicand.
function multiply(a) {
return function (b) {
return a * b;
}
}
var threeTimes = multiply(3);
console.log(threeTimes(7));

Related

What is this js syntax called [duplicate]

This question already has answers here:
What is 'Currying'?
(23 answers)
Closed 4 years ago.
I recently found JavaScript code like this:
someFunction()()
Function immediately invoked right after function without classic IIFE syntax.
What is that kind of syntax called? And how it works?
Its a function that returns another function.
Here is an example on how it works, this can help you to understand better.
function sum(x){
return function(y){
return x+y;
}
}
sum(3)(5); //8
For you code to work:
someFunction()();
You need to have code that looks like this:
function someFunction() {
console.log('someFunction()');
// do something before return
return function() {
console.log('someFunction()()');
// do something else here
}
}
someFunction()();
In this example you first call someFunction then you call the function that was returned by someFunction.
This can be good to do when you need to pass in a variable that will be used in the inner function but the inner function will be called in the future like this:
function someFunction(outerVal) {
console.log('Outer called.');
return function(innerVal) {
console.log('inner called.');
return outerVal * innerVal;
}
}
var inner = someFunction(12);
setTimeout(()=> {
console.log(inner(4));
}, 1000);
I use this often in Node.js for common middle-ware that needs a single value to be unique.
app.get('/dogs', myFn('woof'));
app.get('/cats', myFn('meow'));
app.get('/birds', myFn('tweet'));
function myFn(word) {
return function(req, res, next) {
res.write(word).end();
}
}
That is an over simplification, but can be vary powerful.

why i always getting back as undefined? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am new to Javascript, and Trying to write a function inside a function, but it always show undefine.
function csnotebook(){
function calculate_mw(peptide){
var total_mw=0;
var split_peptide = peptide.split("-");
// Check if the blog id is found in database
Aa.findOne({ three_letter: split_peptide[1] }, (err, aa) => {
// Check if the id is a valid ID
if (!aa) {
console.log("wrong aa");
}else{
total_mw += aa.mw;
}
return total_mw;
});
}
var publicAPI = {
mw: calculate_mw
};
return publicAPI;
}
var fred = csnotebook();
var totalmw = fred.mw("Ala-Cys");
console.log(totalmw);
I assume i can find the corresponding value mw from database, but totalmw, I always get undefined for some reson, anybody know why? Thank you!!
The inner function calculate_mw doesn't return anything, so the return value of a function is undefined unless you return something.
If you want to return the result of the Aa.findOne you should:
return Aa.findOne(...

Getting Value from Function in Javascript

I am a beginner at Javascript and am running into a little problem. It is a homework problem, but it is graded based on completion only, so I am only trying to figure out the right answer for myself.
I am supposed to define a function, repeatUntil, that takes in two other functions, say f(returns a number) and g (returns a boolean value). The functionality of repeatUntil is to repeat function f at least once until g returns true.
Here is what I have so far:
function repeatUntil(f, cond) {
var f1;
do{
f1 = f;
return f1;
}
while(cond(f1()));
}
And here is the tester/how we call it:
var print = console.log;
var r = repeatUntil(function(x) { return x + x }, function(x) { return x >= 20 })
print(r(2))
print("Expected: 32")
The function runs, but my problem right now is storing the updated value of x from the repeatUntil function. Right now the function only runs once, and the condition is not updated because I cannot pass in the updated value of x into the function g. I tried putting the result of f() into a variable, but it will only return a function and not a number.
Any help/advice would be greatly appreciated. Thank you!
Combining the existing comments into an answer.
Since you need to call r(), your function needs to return another function.
The do loop will run exactly once because you return in the body of the loop
Code
function repeatUntil(f, cond) {
return function() {
while(cond(f()));
}
}

explanation of es 6 code [duplicate]

This question already has answers here:
What do multiple arrow functions mean in JavaScript?
(7 answers)
Closed 6 years ago.
Can anyone explain what the code is doing here
return () => next => action => {
const callAPI = action[CALL_API];
if (typeof callAPI === 'undefined') {
return next(action);
}
let { endpoint } = callAPI;
const { types, bailout } = callAPI;
It is initially returning a function but I don't get why there are two further fat arrows after the first.
If the arrow function has only one parameter, then the parameter around that is optional. You just need to have enough parenthesis to understand them better.
return () => (next) => (action) => {
it returns a function, which when invoked returns another function which accepts one parameter, next. Now when that function is invoked, it returns another function, which accepts another parameter action.
That code can be rewritten like below,
return function() {
return function(next) {
return function(action) {
It seems that the outer function returns a function with parameter next and that returns another one function with parameter action. That code in the link that you given has not minified, but that seems to be obfuscated.

confused about return array#map javascript [duplicate]

This question already has answers here:
Can anyone explain why linebreaks make return statements undefined in JavaScript? [duplicate]
(4 answers)
Closed 7 years ago.
I have the code:
function func1(){
return
array.map(function(el){
return el.method();
});
}
function func2(){
var confused =
array.map(function(el){
return el.method();
});
return confused;
}
Why func1 return undefined while func2 return good value (that i need)?
Sorry for my english.
Internally in JS engine first example looks like this,
function func1() {
return;
array.map(function(el){
return el.method();
});
};
that's why you get undefined, don't add new line after return, because return statement followed by a new line tells the JS intepreter that a semi colon should be inserted after that return.
function func1() {
return array.map(function(el){
return el.method();
});
};

Categories