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
Related
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()));
}
}
Sorry, first attempt at explaining this question was poor. Trying to learn Javascript and a question from a code problem (codewars) has me stumped. It states, write a function that takes another function as a parameter and caches results so that if the same parameters are sent then the return is pulled from the cache and the actual function is not invoked again. For example:
var x = function(a, b) { a * b };
var cachedFunction = cache(x);
cachedFunction(4, 5); // function x should be executed
cachedFunction(4, 5); // function x should not be invoked again, instead the cached result should be returned
cachedFunction(4, 6); // should be executed, because the method wasn't invoked before with these arguments
I am not sure how to access the arguments sent via cachedFunction. The goal is to write cache so that it can handle a function x with any number of arguments.
What you're describing is not possible.
The expression x(5, 4) is evaluated before the cache() function is even called. It's not receiving a function. It's receiving the value 20.
In your example, cache only has access to the return value of x. It can't know anything about how this return value was computed (i. e. by calling x with parameters 5, 4).
You would need to separately pass the function and its parameters to the cache function, e. g. as follows:
function cache(func, ...params) {
// Todo: do something with params
return func(...params);
}
function x(a, b){
return a * b;
}
console.log(cache(x, 5, 4));
you can return a table like this:
function x(a,b){
return [a, b, a*b];
}
after that you can get the params like this:
var result=x(values1,value2);
console.log(result[0]);// a == value1
console.log(result[1]);// b == value2
console.log(result[2]);// a*b == value1*value2
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."
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
Can I write a function that returns iteself?
I was reading some description on closures - see Example 6 - where a function was returning a function, so you could call func()(); as valid JavaScript.
So I was wondering could a function return itself in such a way that you could chain it to itself indefinitely like this:
func(arg)(other_arg)()(blah);
Using arguments object, callee or caller?
There are 2-3 ways. One is, as you say, is to use arguments.callee. It might be the only way if you're dealing with an anonymous function that's not stored assigned to a variable somewhere (that you know of):
(function() {
return arguments.callee;
})()()()().... ;
The 2nd is to use the function's name
function namedFunc() {
return namedFunc;
}
namedFunc()()()().... ;
And the last one is to use an anonymous function assigned to a variable, but you have to know the variable, so in that case I see no reason, why you can't just give the function a name, and use the method above
var storedFunc = function() {
return storedFunc;
};
storedFunc()()()().... ;
They're all functionally identical, but callee is the simplest.
Edit: And I agree with SLaks; I can't recommend it either
Yes.
Just return arguments.callee;
However, this is likely to result in very confusing code; I do not recommend it.
You can do what you want as following:
// Do definition and execution at the same time.
var someFunction = (function someFunction() {
// do stuff
return someFunction
})();
console.log(someFunction)
arguments.callee is not supported in JavaScript strict mode.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
Even sorter that all the above is:
f=()=>f
There is a simple way to achieve this doing the following:
let intArr = [];
function mul(x){
if(!x){
return intArr.reduce((prev, curr) => prev * curr)
}
intArr.push(x);
return mul;
}
console.log(mul(2)(4)(2)()); => outputs 16
It is also possible just to return the argument the self invokable function like
console.log( (function(a) { return a; })(1) ); // returns 1