Javascript unknown function parameters

Javascript unknown number of arguments

in my project, I register different functions (having different number of arguments) as listeners to a number of events. When the event takes place, I need to fire the associated function. I receive the parameters to be passed to listener method in the form of an array whereas the listener function expect each separate argument. So, I am doing it like this but I do not like the approach and would like to know if there is an elegant way of doing it,

function callListenerWithArgs(func, args) < switch(args.length)< case 1: func(args[0]); break; case 2: func(args[0], args[1]); break; case 3: func(args[0], args[1], args[2]); break; case 4: func(args[0], args[1], args[2], args[3]); break; default: func(); >> 

Thank you all guys. fun.apply does exactly what I needed. It is simple and sweet 🙂 and addresses my problem precisely.

5 Answers 5

If you need to bind to a specific scope, you can pass another argument in to use as this inside the function:

Also, a nuance of JavaScript is that you can call functions with undefined values. So making a small tweak to your existing code will work in 95% of all cases (this isn’t suggested as a solution, just pointing it out):

// will handle any number of args up to 7 function callListenerWithArgs(func, args)

If your func is defined as:

you get a , b , c passed in, along with some more undefined values that get ignored. As I said above, this works in 95% of cases. It doesn’t work if you ever check arguments.length in the called function since it will always be the same, regardless of the number of parameters the function defines.

Источник

Currying function with unknown arguments in JavaScript

In a recent interview, I was asked to write a function that adds numbers and accepts parameters like this:

add(1)(2)(3) // result is 6 add(1,2)(3,4)(5) // result is 15 

The number of parameters is not fixed, and the arguments can be either passed in sets or individually. How can I implement this add function?

So you want to implement currying a variadic function? I’d argue that’s not possible, but there are many related questions on SO. E.g. stackoverflow.com/q/38638644/218196

I’m sure you did some attempt in your presumed interview, why didn’t you make any here? Also it’s very close to this kata from codewars, you can look at solutions by opting out of the related kata. Also note that the description of your function is not proper — is the result returned after exactly three calls every time or what?

@ASDFGerte: I am not sure what you mean by ‘opting out of the related kata’. I don’t see any solution mentioned there, just the option of taking that challenge!

Читайте также:  Have java runtime environment jre version 8

I know. What you want is simply not possible, if you really want to to curry a variadic function. Think about it: Currying means to return a function of lower arity if not all arguments are passed, eventually returning the result if all arguments have been passed. But since a variadic function accepts an unlimited number of arguments, you don’t know when it is done. Hence the use of «hacks» in the other question.

4 Answers 4

Given your examples, the number of parameters is fixed in some ways.

As @ASDFGerte pointed out, your examples seem to return the result after three invocations. In this case a simple implementation without introducing terms like variadic and currying could be

function add(. args1)< return function(. args2)< return function(. args3)< return args1.concat(args2).concat(args3).reduce((a,b)=>a+b)>>> console.log(add(1)(2)(3)) console.log(add(1,2)(3,4)(5))

Every invocation accepts a variable number of parameters.

However it would be nice to generalize the construction of this nested functions structure and you can accomplish that with currying.

But if you want to allow an arbitrary number of invocations, when you should stop returning a new function and return the result? There is no way to know, and this is a simple, unaccurate and partial explanation to give you the idea of why they said you cannot accomplish what they asked you.

So the ultimate question is: is it possible that you misunderstood the question? Or maybe it was just a trick to test you

Another option would be to actually invoke the function when no arguments are passed in, change the call to add(1)(2)(3)()

Here an example recursive implementation

function sum (. args) < let s = args.reduce((a,b)=>a+b) return function (. x) < return x.length == 0 ? s : sum(s, . x) >; > console.log(sum(1,2)(2,3,4)(2)())

At every invocation computes the sum of current parameters and then return a new function that:

  • if is invoked without parameters just return the current sum
  • if other numbers are passed in, invokes recursively sum passing the actual sum and the new numbers

Источник

unknown parameters in node.js

I’m looking at the Yahoo Finance API, which can be found here and here as well. I’m new to node.js, so this is a pretty simple question. In the var buildfn = function(csvfile, headers) function, another function is called, var response2console = function(result, response) . I’ve read up on closer, what I don’t understand is where the parameters (result, response) in the second function, response2console, come from. They are not global variables, and they aren’t defined locally in the function either, so how are they defined?

1 Answer 1

They’ll come from when the function is called.

var marketResearch = function(symbols, columns, csvfile, headers) < symbols = symbols || SYMBOLS_DEFAULT; columns = columns || COLUMNS_DEFAULT; csvfile = csvfile || CSVFILE_DEFAULT; headers = headers || HEADERS_DEFAULT; var apiurl = financeurl(symbols, columns); var response2console = buildfn(csvfile, headers); rest.get(apiurl).on('complete', response2console); >; 

but the response2console var in the marketResearch is not the same as the response2console in the buildfn, correct? I mean I know they are set equal to each other, but they aren’t the same in that when response2console is called in the bulidfn function, it does not define response2console in the marketResearch function

Читайте также:  Server functions in php

response2console here is the return value of buildfn(csvfile, headers); , so it is the same as the response2console defined there since that is the return value of buildfn .

alos, I still dont understand the values given to the parameters (result, response) are those parameters just set equal to (csvfile, headers) when response2console is called?

Источник

Checking for missing parameter in function

Is this the correct way to check for a missing parameter in a function? Would this work in all browsers? How about IE?

How does one define «correct» in this instance? To give you the best answer, we’d need to know the contexts in which the parameter should be overwritten.

Recently, I asked whether it was possible to list the names of each missing parameter in a JavaScript function, and I found plenty of interesting solutions here: stackoverflow.com/questions/17387222

4 Answers 4

The way to check for parameters depends on what type of information you’re passing to the function, and how you want your function to handle edge cases.

In most cases, you can use:

. bar = bar || . default value here. . 

However, it might be an issue when you want to pass in falsey values ( false , 0 , NaN , » , undefined , null ):

function foo(bar) < bar = bar || 5 console.log(bar) >foo() // 5 foo(undefined) // 5 foo(null) // 5 foo(1) // 1 foo(0) // 5, probably not what you wanted

Instead, you can check against undefined :

. however using the loose check allows both null and undefined to be overwritten ( null == undefined ):

function foo(bar) < if (bar == undefined) < bar = 5 >console.log(bar) > foo() // 5 foo(undefined) // 5 foo(null) // 5 foo(1) // 1

So instead, a strict equality comparison ( === ) is generally preferred ( null !== undefined ):

function foo(bar) < if (bar === undefined) < bar = 5 >console.log(bar) > foo() // 5 foo(undefined) // 5 foo(null) // null foo(1) // 1

ES2015 introduced default parameters, which are essentially equivalent to strict checking against undefined :

function foo(bar = 5) < console.log(bar) >foo() // 5 foo(undefined) // 5 foo(null) // null foo(1) // 1

This could lead to trouble if you need to know whether undefined was passed as a parameter.

If you want to be absolutely certain that you’re not passing up an argument that was provided, you can check the number of arguments passed to the function:

Which means that you can successfully pass undefined as an argument while also choosing to use a different default:

function foo(bar) < if (arguments.length < 1) < bar = 5 >console.log(bar) > foo() // 5 foo(undefined) // undefined foo(null) // null foo(1) // 1

If you have multiple parameters, you may want to use multiple defaults. I’ve recently found a use case for fallthrough on a switch statement, although the utility is questionable:

function foo(bar, baz, fizz, buzz) < switch (arguments.length) < case 0: bar = 1; //continue; might as well point out that implicit fall-through is desired case 1: baz = 2; //continue; case 2: fizz = 3; //continue; case 3: buzz = 4; //continue; >console.log(bar, baz, fizz, buzz) > foo() // 1 2 3 4 foo(10) // 10 2 3 4 foo(10, 20) // 10 20 3 4 foo(10, 20, 30) // 10 20 30 4 foo(10, 20, 30, 40) // 10 20 30 40

Источник

Читайте также:  Intellij idea создать java файл

Javascript : Function parameter is undefined

You can only “examine” the type of undeclared variables directly with the typeof operator. You can’t pass undeclared variables.

if you need this kind of work around, you may better use ‘use strict’; and declare all variables. the only use is actually the check of a property which is not set.

3 Answers 3

See this post. You have to understand the difference between undefined and undeclared variables.

var x; //undefined until assignment; isUndefined(x); // returns true; 

Basically, undefined represents value, which are not defined formally by user. Consider your example :

var isUndefined = function(obj)< return typeof obj == 'undefined'; >; 

So, isUndefined() when invoked without any argument, then the value of obj will be undefined in the function.

Variable x is not declared but you are asking typeof in global context

typeof x === 'undefined' // Returns true 

Which is equivalent to below

typeof window.x === 'undefined' //True 
x === undefined //Throws error 

as the variable is never set or declared in the global scope with any standard JavaScript datatypes.

Read MDN blog, Which states that :

JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object

Now when calling the isUndefined function you will be passing the reference of the variable x which is not declared in the parent scope and runs the code in functional scope trying to take the reference of x .

As x is no where declared, there is no meaning or value to be passed by javascript interpreter at runtime to isUndefined . Hence throws the Reference error asking the develeper to atleast declare the variable which when not assigned any value will be set default to primitive type undefined .

Now by setting x to primitive type undefined explicitly as below

var x; // Equivalent to window.x 
var x = undefined; //Equivalent to window.x = undefined 

Now the JavaScript interpreter is aware that there a variable called x declared in global scope window and is set to primitive datatype. Below statements become true :

typeof x === 'undefined' // Returns true x === undefined //Returns true x in window // Returns true isUndefined(x) // Returns true 

Источник

Оцените статью