Find which parameters a higher order function contains - javascript

I have a function that accepts a function as an argument.
This callback function can receive up to 5 parameters. Any of these can be null at some point.
I tried accessing the arguments property, but it throws this error:
'caller', 'callee', and 'arguments' properties may not be accessed on strict mode.
Is it possible to find which arguments this function received? So i don't have to pass it all 5 each time?
function bar(callback){
// do some stuff
return callback(first, second, third, fourth, fifth)
}
Some use cases I'm having:
bar((a, b, c) => a + c)
bar((a, b, c, d) => a + c + d)
bar((a, b, c, d, e) => a + b + e)
I'm always calling the callback with 5 arguments, but sometimes, not all of them are being used. And for each one, I'm doing some computation.
Another example:
If I call the function like this:
bar((a, b, c, d, e) => a + b + e)
And my function defined like this:
function bar(callback){
// do some stuff with
return callback(first, second, third, fourth, fifth)
}
There would be no need for me to pass the third and fourth parameters to the callback, because they are null. But since I don't have access to the arguments the callback has received, I'm not being able to do this.

You could use Function.length,
function func1() {}
function func2(a, b) {}
console.log(func1.length);
// expected output: 0
console.log(func2.length);
// expected output: 2
But, I would not advice writing code that relies on this. The callback function could be implemented in different ways that this wouldn't work. Some examples:
function callback(){
console.log(arguments); // could access all parameters but length is 0
}
function callback(...args){
console.log(args); // could access all parameters but length is 0
}
function callback(a,b=0,c,d,e){
console.log(a,b,c,d,e); // could access all parameters but length is 1
// 1, only parameters before the first one with
// a default value is counted
}
A better solution would be not overloading the function with different behaviors depending on what the callback expects, and actually tell what you should "return" to the callback
function bar(callback, n){
if(n===0) // do something
else if(n===1) // do something else
}
Or don't write "overloaded" functions that have multiple behaviors, and actually having multiple functions:
function foo(callback){
// do some sutff
return callback(first, second)
}
function bar(callback){
// do some sutff
return callback(first, second, third, fourth, fifth)
}
EDIT: from your last edit you should need to have something like this
function bar(params, callback) {
const obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
};
const args = params.map(p => obj[p]);
return callback.apply(this, args);
}
console.log(bar(['a', 'b'], (a, b) => a + b)) //3
console.log(bar(['a', 'd', 'e'], (a, d, e) => a + d + e)) //10

You could take the Function#length property of the function, which returns the number of defined parameters.
function bar(callback) {
console.log(callback.length);
}
bar((a, b) => a + b);
bar(function (a, b, c) { console.log(a, b, c); });

Related

What does "a.call.apply(a.bind, arguments)" mean?

Just because of curiosity I wanted to make a bounded function with this particular approach :
var fn = function(a, b, c) {
return a.call.apply(a.bind, arguments)
}
var boundFn = function(a, b, c) {
fn.apply(null, arguments)
}
function unboundedFn() {
console.log(this, arguments)
}
var boundedFn = boundFn(unboundedFn, x, y);
So I'm trying to understand what a.call.apply(a.bind, arguments) do exactly ?
If You have a function like this:
function unboundedFn() {
console.log(this, arguments)
}
You can use unboundedFn.call(thisObj, arg1, arg2) or unboundedFn.apply(thisObj, [arg1, arg2]) to run it, but changing what this means inside. Both call and apply do the same, and only difference is way of passing arguments.
Becouse call, apply and also bind are methods, you can run for example unboundedFn.call.call.call.call.apply.apply.apply.apply(), but it doesn't seem to have to much sense.
In your example return a.call.apply(a.bind, arguments) is equal to return a.bind.call(...arguments), which is equal to a.bind(...arguments.slice(1)), so whole fn function can be simplified to:
function fn(a,b,...args){
return a.bind(b, ...args);
}

input function into other function

i'm trying to input a function into another function and then running it.
I have a function.
function example_function() {
document.print('example')
and I would like to input into another function to have it executed N times.
function do_n_times(function, times) {
for (var i = times; i < times; i++) {
do(function)
}
}
Is there a way to do this, and if so. Can you also do custom inputs?
function do_n_times_with_this_input(function, times, input) {
for (var i = times; i < times; i++) {
do(function(input))
}
}
You can absolutely do this! JavaScript has what's called first-class functions, which means they can be passed around just like any other variable. The syntax for that looks like this:
function example_function() {
console.log('example')
}
function do_n_times(func, times) {
for (var i = 0; i < times; i++) {
func();
}
}
do_n_times(example_function, 5);
Yes, you can do what you describe. In JavaScript, you can call any variable as a function by appending () at the end:
function f1() {
console.log("f1 called")
}
const f2 = () => console.log("f2 called");
const nonFn = 42;
f1();
f2();
try {
nonFn();
} catch (e) {
console.log("Error because nonFn is not a function")
}
You can further pass functions in any way you want:
function f1() {
console.log("f1 called")
}
const f2 = () => console.log("f2 called");
function caller(fn) {
fn();
}
caller(f1);
caller(f2);
caller(() => console.log("directly defined arrow function called"));
caller(function() { console.log("directly defined normal function called"); });
Which also means that you can pass any input you want as well:
function f1(input) {
console.log("f1 called with", input)
}
const f2 = input => console.log("f2 called with", input);
function caller(fn, input) {
fn(input);
}
caller(f1, "foo");
caller(f2, "bar");
caller(
input => console.log("directly defined arrow function called with", input),
"baz"
);
caller(
function(input) { console.log("directly defined normal function called with", input); },
"quux"
);
This is the basic stuff, you can have more control over how you execute a function by using Function#call and Function#apply. In both cases that allows you to execute a function and change its context
function f() {
console.log("f called with context:", this);
}
function caller(fn) {
const newContext = {foo: "hello"}
fn.call(newContext);
}
function applier(fn) {
const newContext = {bar: "world"}
fn.apply(newContext);
}
caller(f);
applier(f);
You can also pass arguments in both cases. The difference between .call() and .apply() is in what form you pass them. And if you don't care about the context (the function is not using this) then you can just use null as the argument for that:
function f(a, b, c) {
console.log(
"f called with arguments",
"\n\ta:", a,
"\n\tb:", b,
"\n\tc:", c
);
}
function caller(fn, a, b, c) {
fn.call(null, a, b, c);
}
function applier(fn, a, b, c) {
fn.apply(null, [a, b, c]);
}
caller(f, "passed", "directly", "into");
applier(f, "passed", "as", "array");
The difference seems negligible but here is a real good use-case for .apply - you can supply infinite arguments to a function:
function f(...args) {
console.log(
"f called with arguments:", args
);
}
function applier(fn) {
const argumentsForFunction = Array.prototype.slice.call(arguments, 1);
fn.apply(null, argumentsForFunction);
}
applier(f, "one");
applier(f, "alpha", "beta", "gamma");
applier(f, "a", "b", "c", "d", "e", "f", "g");
Notice how Array#slice was called with the arguments object in order to exclude the first item (the function) and take the rest.
You can get quite a lot of control over how a function is executed. using these.
A final option is Function#bind - it works a lot like call in that you can change the context and pass arguments but the difference is that it returns a new function that will always use these. This has useful applications - you can permanently set this so you never "loose" it.
Another useful application of the .bind() method is creating called "partially applied function" - this is a function that normally takes multiple parameters but you've permanently set some of them, so the function only waits for the remaining ones or even just for execution:
function f(a, b) {
console.log(
"f called with arguments",
"\n\ta:", a,
"\n\tb:", b
);
}
//null for the context - we don't care for it here
const f1 = f.bind(null, "hello");
f1("world");
f1("my baby");
f1("my honey");
const f2 = f1.bind(null, "my ragtime gal");
f2();

How to pass a function with arguments to a function as argument in javascript? [duplicate]

This question already has answers here:
Passing a function with parameters as a parameter?
(7 answers)
Closed 3 years ago.
I'm new to javascript and I was learning higher-order functions where I learned about passing functions as arguments to other functions. How can I pass a function with arguments to a function?
I want to pass the function's arguments when passing the function as parameter to the main function.
example :
function fubar(a,b,fun(c,d)){
//execute here
}
and not like this
function fubar(a,b,fun()){
fun(a,b)
}
Here's an example, just pass it like a regular argument, no specific syntax is required :)
// define the function argument like a regular argument
function fubar(a, b, fn){
// call that argument like a function
return fn(a, b);
}
// sample function
function add(c, d){
return c + d;
}
// pass the "add" function like a regular argument
let result = fubar(1, 2, add);
console.log(result);
You just need to pass the name of the function as the parameter, just like another variable.
for example :
foobar(5, 10, baz, ham);
function foobar(a, b, fn1, fn2){
...
fn1(); // call the baz function.
res = fn2(a,b); // calls ham func with a and b as parameter
console.log(res)
...
}
function baz(){
console.log("Inside the Baz function ");
}
function ham(s,t){
console.log(s, t);
return s+t;
}
If you're asking how to pass a function that will execute with some pre-determined arguments, you can do so using another function.
For example
const a = 'a'
const b = 'b'
const c = 'c'
const d = 'd'
function fubar(a, b, fn) {
console.info('func:', a, b, fn()) // executing "fn()" here
}
function fun(arg1, arg2) {
console.info('fun:', arg1, arg2)
return 'return value from fun' // just an example so you can see it in fubar()
}
fubar(a, b, () => fun(c, d))
Here, () => fun(c, d) is an self-contained, anonymous arrow function (or "lambda") that when called, will execute fun(c, d).

Why is it necessary to pass existing arguments to `setTimeout` again?

Why is it necessary to write a and b after mls in the setTimeout method here? Aren’t a and b already defined in the arrow function?
function f(a, b) {
alert(a + b);
}
// shows 3 after 1 second
Function.prototype.defer = function(mls) {
return (a, b) => setTimeout(this, mls, a, b);
}
f.defer(1000)(1, 2);
Because f.defer(1000) returns the arrow function which in turn gets called with (1,2) as parameter. This arrow function is calling setTimeout which is supposed to call the same function f with these parameters 1 and 2. And the definition of seTimeout states that you can pass parameter to the callback function after first 2 parameters. Please refer below definition and link for the reference.
window.setTimeout(function[, delay, param1, param2, ...]);
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
The arrow function is defining a function that then invokes setTimeout(this, mls, a, b). It could also be written as:
Function.prototype.defer = function(mls){
var that = this;
return function(a,b) {
setTimeout(that, mls, a, b);
}
}
This is important to note because you're actually returning a function from defer. So when you call f.defer(1000), the return value is a function - your arrow function, to be specific - and then you invoke that function with the values 1 and 2 when you call f.defer(1000)(1, 2);.
If you don't, your function will not be called with any parameters. These parameters are passed into the originally invoked function.
setTimeout takes a variable number of arguments. The first one is the function (this, or f in this case), the second one is the delay. Any argument after that is passed to the to-be-called function upon calling it.
Your function f expects two arguments; if they aren’t passed, they are undefined. There are indeed an “a and b already defined in the arrow function”, but they are scoped to the arrow function. If a function calls another function, its arguments aren’t automatically transfered.
Internally, setTimeout is doing something like outerWorking in this example:
const inner = (a, b) => a + b,
outerWorking = (a, b) => inner(a, b),
outerNotWorking = (a, b) => inner();
console.log(outerWorking(2, 3)); // 5
console.log(outerNotWorking(2, 3)); // NaN
So f.defer(1000) returns a new function with mls === 1000 and this === f. It accepts a and b which are yet to be defined with the next function call (calling the arrow functions, with the argument list (1, 2)). Only when you pass a, b at f.defer(1000)(1, 2), then setTimeout(this, mls,a,b) will be called with a === 1, b === 2 and the other two bindings above (this and delay).
Alternatively, this could be written as
Function.prototype.defer = function(mls, a, b){
setTimeout(this, mls, a, b);
};
f.defer(1000, 1, 2)
But there’s an advantage in the original, curried approach, as you can simply detach the “defered function” from the final call:
const add1sDelay = f.defer(1000);
add1sDelay(1, 2);

extract parameters from callback outside of the callback

How can I extract the arguments (a, b) of a callback-function and add another
parameter (c) to the function-call?
function mycallback(a, b, c) {
// do stuff with a, b, c
}
function perform(callback) {
// I need to extract a and b here and add c:
// ???
//callback.apply(???);
}
perform( function() { mycallback(1, 2) } );
The only way I can think of is to pass the parameters to perform itself and then let it pass them along to the callback:
function perform(callback) {
var args = Array.prototype.slice.apply(arguments).splice(1);
// use args... add c with args.push(c)...
callback.apply(this, args);
}
perform(mycallback, 1, 2);

Categories