Getting Value from Function in Javascript - 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()));
}
}

Related

function()(function) in javascript what does this syntax standard? [duplicate]

I was looking how filters works in Angularjs and I saw that we need to send 2 sets of parentheses.
$filter('number')(number[, fractionSize])
What does it means and how do we handle it with JavaScript?
It means that the first function ($filter) returns another function and then that returned function is called immediately. For Example:
function add(x){
return function(y){
return x + y;
};
}
var addTwo = add(2);
addTwo(4) === 6; // true
add(3)(4) === 7; // true
$filter('number') returns a function that accepts two arguments, the first being required (a number) and the second one being optional (the fraction size).
It's possible to immediately call the returned function:
$filter('number')('123')
Alternatively, you may keep the returned function for future use:
var numberFilter = $filter('number');
numberFilter('123')
It is the same as this:
var func = $filter('number');
func(number[, fractionSize]);
The $filter() function returns a pointer to another function.
with ES6 or later versions you can do it that way;
const divideBoth = (x) => (y) => {
return x / y;
};
one of the reasons that makes this function type useful is when you have a react.js component that needs have callback function instead of doing it inline way(which is ()=>return value) you can do it the way we did previously. But it is not recommended to use in event callbacks because it gets execute in the first render which might cause issues sometimes

javascript syntax questioon

So let's say I have the following code:
function c (f,i) {
let x = i;
if (f(x,i)){
x--;
}
if (f(x,2)) {
console.log(1);
}
else {
console.log(2);
}
}
what exactly happens in the if statements, I don't understand the syntax behind it.
f is no function, it's a variable, so what happens here? does it equal to f * ( x * i)? whats the operands behind this syntax.
Thanks in advance
A variable can also hold a function. It's possible to call c like this:
c(function(x, i) {/* do some check with x and i */}, 10);
In the if statements, the function you pass is called to do a check. A function like this is called a callback function. You have to pass it to the c function as in the example above. So if you call c, you can also determine how the check is done that c does.

How does a reference in closure and currying work in js?

The following program confuses me very much, the console.log() were added by me.
function add(a) {
console.log("1");
var total = a;
console.log("2");
var _fn = function (b) {
console.log("3");
total += b;
console.log("4");
return _fn;
};
console.log("5");
_fn.toString = _fn.valueOf = function () {
console.log("6");
return total;
};
console.log("7");
console.log("_fn: " + _fn);
return _fn;
}
When I ran add(1)(2), console showed:
1
2
5
7
6
_fn: 1
3
4
6
ƒ 3
My questions are:
1) in var _fn = function (b) {...}, what does _fn refer to in "return _fn" statement? If it refers to itself, then isn't it in infinite recursion like this
var _fn = function (b) {
total += b;
return function (b) {
total += b;
return function (b) {
total += b;
return _fn;
.
.
.
}
}
}
2) In console, it showed "_fn: 1" which means 1 was returned, but apparently, _fn (the function) was returned so that the calculation could keep going. So there is a conflict between the actual returned _fn and the value shown in console.
in var _fn = function (b) {...}, what does _fn refer to in "return _fn" statement?
The return statement says the when this function is called, the return value from the function will be (a reference to) the function object itself. Note it returns the function object, without calling it. Just the object, no call. At least not yet anyway....
If it refers to itself, then isn't it in infinite recursion like this ...
No, because the return value, the function, is not immediately called. It's kind of like doing this:
function g() {return g}
g()
Running that does not go into an infinite loop. You call the function g, and you get back g. You can do g()()()()()()() yourself, but that still "stops." Recursion is when a function calls itself, not returns itself!
In console, it showed "_fn: 1" which means 1 was returned, but apparently, _fn (the function) was returned so that the calculation could keep going. So there is a conflict between the actual returned _fn and the value shown in console.
Well, it's probably not correct to say 1 was returned; instead the code forces all console.logs (and similar) to produce the current value of total. At the time you did your console.log, total had the value of your first argument, namely 1. You were pretty smart to print out all those numbers, so it should help your understanding. Check out that after the 7 was printed, you had not yet done the subsequent call in which the addition was done. That's why you saw 1.

Difference between js functions by using parameters

What's the difference between:
// Example 1 sum(8,2)
console.log(sum(8,2)); // Outputs what??
// Example 2 sum(8)(2)
console.log(sum(8)(2)); // Outputs what??
function sum(x,y) {
return x+y;
}
function sum(x) {
return function(y){
return x+y;
}
}
Why is one used over the other and why?
What you are trying to do is called Function Currying
Try this:
function sum(x) {
return function(y) { return x + y; }
};
var sumWith4 = sum(4);
var finalVal = sumWith4(5);
finalVal = sumWith4(8);
One of the advantages is that it helps in reusing abstract function. For example in the above example I can reuse sumWith4 to add 4 to any number with out calling sum(4,5) explicitly. This was a very simple example. There would be scenarios where in part of the function would be evaluated based on the first param and the other part on the second. So you can create a partial function by providing it with the first param and then reuse the partial function repeatedly for multiple different second params.
I will be assuming that you mean to ask the difference between the invocation of functions which appear like:-
someFunction(x, y)
someFunction(x)(y)
This happens with the use of Closures which happens to be a concept wherein an inner function can carry the environment in which it was created.
var sum = function (x){
return function(y) {
return x+y;
};
};
var addWith5 = sum(5);
/*
This will return a function and not a value
addWith5 = function(y){return 5+y;};
*/
console.log(addWith5(5)); // this will return 11
/*
You can also use add function directly
*/
console.log(sum(5)(6)); // this will return 11
/*
The function returned by sum(5), gets called with the parameter (6)
*/
//Try using this, to make it more clear
function a(x){
return x;
}(5);
// returns 5
EDIT
Removed "closures is a JS concept."

Higher order javascript functions

can someone explain to me what is going on in the following code. The function is receiving n as parameter, so where is the m coming from? The whole code is confusing.. if someone can explain?
function greaterThan(n) {
return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// → true
This is exhibiting a functional programming technique called currying. (related also to partial function appliction)
Greater than > usually takes 2 arguments (one on the left and one on the right). This is a way to feed one at a time.
It might be easier to see what is happening if you call it inline:
greaterThan(10)(11);
As you can see from the example above, the 10 gets passed in for the n parameter and then the 11 gets passed in for the m parameter.
The first application that passes the 10 outputs a function that looks like this:
function(m) { return m > 10; };
This is the first application in the partial application.
From there it is easy to see how the 11 is passed in to get the final result.
So, to break it down:
function greaterThan(n) {
return function(m) { return m > n; };
}
//var greaterThan10 = greaterThan(10); -- is equivalent to:
var greaterThan10 = function(m) { return m > 10; };
console.log(greaterThan10(11)); //--> true
m is 11, passed in during the second call.
When you call greaterThan(10), it returns a new function that looks like:
function(m) {
return m > 10;
}
which is then saved as greaterThan10. This is called currying.
greaterThan is a function that returns another function as a result, m is a paraterer of that returned function. So in your code:
var greaterThan10 = function(m) { return m > 10; };
and
console.log(greaterThan10(11)); is the same as console.log(11 > 10);
when you call function greaterThan it returns another function but not a number of float. Inner function knows about n because it inside function greaterThan.
Because wrapper function returns another function you can call second one like this
var result = greaterThan(10)(11);
first argument 10 will be used for wrapper function but result is function so you can pass arguments for inner function immediately.
this is possible only if you have return function(){...}
you can try something like
var a = function (x){
return function(y){
return function(z){
return x*y*z;
}
}
}
var result = a(5)(3)(8);
You have two functions there.
The n comes from when the first function is called.
The m comes from when the second function (which is the return value of the first function) is called.
greaterThan10 = greaterThan(10);
// ^^ n
greaterThan10(11))
// ^^ returned function
// ^^ m

Categories