Variable number of arguments in a function - javascript

Is it possible to tell a function what names it should give to its arguments, based on the number of arguments passed? Like this:
function soSwag(swagLevel, swagStart, swagDuration || swagStart, swagStop){}

What some popular libraries (e.g. jQuery) that support variable types of arguments do is that they examine the arguments and then swap values accordingly:
function soSwag(swagLevel, swagStart, swagDuration) {
if (arguments.length === 2) {
var swagStop = swagStart; // 2nd arg becomes swagStop
swagStart = swagLevel; // first arg becomes swagStart
// code here that uses swagStart and swagStop
// as called like soSwag(swagStart, swagStop)
} else {
// code here that uses swagLevel, swagStart, swagDuration
// as called like soSwag(swagLevel, swagStart, swagDuration)
}
}

Not to my knowledge. However, you can just pass in an object with the data you want.
soSwag({
swagStart: 10,
swagStop: 100
});
However, it might be cleaner to simply pass null into that first parameter.

Related

design pattern in javascript

In You don't know JS type & grammar, a design pattern called "dependency injection" is shown in the end of the chapter 1, which I know is not point of this chapter, but I was confused by the example.
the example code is here:
function doSomethingCool(FeatureXYZ) {
var helper = FeatureXYZ ||
function() { /*.. default feature ..*/ };
var val = helper();
// ..
}
So I want to use this function.
Because I don't know whether the FeatureXYZ exists, I dont know how to use it.
doSomethingCool() will not use the FeatureXYZ and doSomethingCool(FeatureXYZ) will throw error if no FeatureXYZ exists. Thus, the function may be a meaningless function.
You can use default parameters to set a default function to call if no parameter is passed, or use the parameter instead if passed to the function.
Use bracket notation to reference the property "FeatureXYZ" at either window object or the object which "FeatureXYZ" is expected to be a property. Bracket notation should not throw an error if the property is not defined at the object.
function FeatureXYZ () {
return {def:456}
}
function doSomethingCool(FeatureXYZ = window["FeatureXYZ"] /* obj["FeatureXYZ"] */) {
var helper = FeatureXYZ || function config() {
/*.. default feature ..*/
return {abc:123}
};
var val = helper();
// ..
return val
}
console.log(doSomethingCool());
Basically, the || operator returns the first value if it's not null or undefined. If it is, it returns the second value. Example:
var x = null;
var y = x || 5;
x is null, hence z will be set equal to 5. If x would be, for example, 4, y would be set to 4 as well.
JavaScript has the feature (or oddity, depends on the viewer), that you do not have to pass every parameter a function has. For example, if you have the following function:
function(x, y) {
return x * (y || 5);
}
It would not result in an error if you call the function without passing y, because it would multiply x by 5 if y is not provided (and therefore undefined).
This is how the example works: It sets helper equal to FeatureXYZ, or, if it is not passed as an argument, e.g. doSomethingCool() (and therefore undefined), it is set to a default function. That way later in the code, when you execute helper(), you either use the passed function, or the default one, if it's not given.

How to use a named function with for each and this

I have found that not using anonymous functions has made my code more readable and self-documenting by flattening the code into more understandable, standalone functions. So I'd like to break out the following construct from:
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(function(index,element) {
if ($(this).val() === myVal) {}
});
}
Into:
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(myFunction);
}
function myFunction(index,element) {
if ($(this).val() === myVal) {}
}
The problem with using .bind here, is that you lose the value of $(this) inside the each method, so (I don't think) I can bind myVal to myFunction.
Maybe I could use element instead of this?
Edit 1: I should have used .myClass instead of #myID for an example selector.
Edit 2: I'm not using bind in the proposed solution because I don't think bind would work.
Edit 3: I appreciate everyone saying that the first example is more readable. I'm just exploring the language and trying out different thoughts.
And what about :
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(myFunction(myVal));
}
function myFunction(myVal) {
return function(index, element) {
if ($(this).val() === myVal) {}
}
}
You're not losing access to this; you're losing access to myVal because myVal is not known inside myFunction, mainly due to that function being defined in a scope that does not have a definition for myVal.
What you can do is something like this:
function myFunction(index, element, myVal) {
if ($(this).val() === myVal) {}
}
and then:
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(function(index, element) {
myFunction.call(this, index, element, myVal);
});
}
This way if you have a lot of logic inside myFunction, you can still separate it out and just call myFunction from .each)'s callback. Not that myFunction is being called with .call because that way you can pass in an explicit value for this (the first argument). Hence this is the same this that is inside the callback to .each.
To be honest though, the first option is much more readable and you really aren't gaining much by splitting your code out like this.
this in this context will be the same. The one thing you lose access to is myVal. You are right that you can't use Function.bind because that does not allow you to specify to keep the original (call time) this
Here's how you can pass myVal and keep the same this, using a modified version of Function.bind, that we're calling myBind
/**
* Binds the given function to the given context and arguments.
*
* #param {function} fun The function to be bound
* #param {object} context What to use as `this`, defaults
* to the call time `this`
* #param {object[]} customArgs Custom args to be inserted into the call
* #param {number} index Where to insert the arguments in relationship
* to the call time arguments, negative numbers count from the end.
That is, -1 to insert at the end. Defaults to a 0 (beginning of list).
*
*/
function myBind(fun, context, customArgs, index) {
return function() {
// Default the index
index = index || 0;
// Create the arguments to be passed, using an old trick
// to make arguments be a real array
var newArgs = Array.prototype.slice.call(arguments, 0);
// Tack the customArgs to the call time args where the user requested
var spliceArgs = [index, 0].concat(customArgs);
newArgs.splice.apply(newArgs, spliceArgs);
// Finally, make that call
return fun.apply(context || this, newArgs);
}
}
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(
// myFunction wil be called with myVal as its last parameter
myBind(myFunction, null, [myVal], -1)
);
}
function myFunction(index, element, myVal) {
if ($(this).val() === myVal) {
// do it here
}
}
To demonstrate the flexibility of this function, let's bind more than one argument, and it should be inserted at the beginning of the call time arguments
function Save() {
var myVal = 3.14, val2 = 6.28; // some arbitrary values
$('#myID').each(
// myFunction wil be called with myVal and val2 as its first parameter
myBind(myFunction, null, [myVal, val2], 0);
);
}
// Since I don't need element, it's already available as this, we don't
// declare the element parameter here
function myFunction(myVal, val2, index) {
if ($(this).val() === myVal || $(this.val() === val2)) {
// do it here
}
}
This is almost the same answer as Samuel Caillerie. The only difference is that we create a different version of Function.bind that doesn't bind this, just the arguments. Another benefit of this version is that you can choose where the insert the bound arguments;

Force missing parameters in JavaScript

When you call a function in JavaScript and you miss to pass some parameter, nothing happens.
This makes the code harder to debug, so I would like to change that behavior.
I've seen
How best to determine if an argument is not sent to the JavaScript function
but I want a solution with a constant number of typed lines of code; not typing extra code for each function.
I've thought about automatically prefixing the code of all functions with that code, by modifying the constructor of the ("first-class") Function object.
Inspired by
Changing constructor in JavaScript
I've first tested whether I can change the constructor of the Function object, like this:
function Function2 () {
this.color = "white";
}
Function.prototype = new Function2();
f = new Function();
alert(f.color);
But it alerts "undefined" instead of "white", so it is not working, so I've don't further explored this technique.
Do you know any solution for this problem at any level? Hacking the guts of JavaScript would be OK but any other practical tip on how to find missing arguments would be OK as well.
If a function of yours requires certain arguments to be passed, you should check for those arguments specifically as part of the validation of the function.
Extending the Function object is not the best idea because many libraries rely on the behavior of defaulting arguments that are not passed (such as jQuery not passing anything to it's scoped undefined variable).
Two approaches I tend to use:
1) an argument is required for the function to work
var foo = function (requiredParam) {
if (typeof requiredParam === 'undefined') {
throw new Error('You must pass requiredParam to function Foo!');
}
// solve world hunger here
};
2) an argument not passed but can be defaulted to something (uses jQuery)
var foo = function (argumentObject) {
argumentObject = $.extend({
someArgument1: 'defaultValue1',
someArgument2: 'defaultValue2'
}, argumentObject || {});
// save the world from alien invaders here
};
As others have said, there are many reasons not to do this, but I know of a couple of ways, so I'll tell you how! For science!
This is the first, stolen from Gaby, give him an upvote! Here's a rough overview of how it works:
//example function
function thing(a, b, c) {
}
var functionPool = {} // create a variable to hold the original versions of the functions
for( var func in window ) // scan all items in window scope
{
if (typeof(window[func]) === 'function') // if item is a function
{
functionPool[func] = window[func]; // store the original to our global pool
(function(){ // create an closure to maintain function name
var functionName = func;
window[functionName] = function(){ // overwrite the function with our own version
var args = [].splice.call(arguments,0); // convert arguments to array
// do the logging before callling the method
if(functionPool[functionName].length > args.length)
throw "Not enough arguments for function " + functionName + " expected " + functionPool[functionName].length + " got " + args.length;
// call the original method but in the window scope, and return the results
return functionPool[functionName].apply(window, args );
// additional logging could take place here if we stored the return value ..
}
})();
}
}
thing(1,2 ,3); //fine
thing(1,2); //throws error
The second way:
Now there is another way to do this that I can't remember the details exactly, basically you overrride Function.prototype.call. But as it says in this question, this involves an infinite loop. So you need an untainted Function object to call, this is done by a trick of turning the variables into a string and then using eval to call the function in an untainted context! There's a really great snippet out the showing you how from the early days of the web, but alas I can't find it at the moment. There's a hack that's required to pass the variables properly and I think you may actually lose context, so it's pretty fragile.
Still, as stated, don't try and force javascript to do something against its nature, either trust your fellow programmers or supply defaults, as per all the other answers.
You can imitate something like Python’s decorators. This does require extra typing per function, though not extra lines.
function force(inner) {
return function() {
if (arguments.length === inner.length) {
return inner.apply(this, arguments);
} else {
throw "expected " + inner.length +
" arguments, got " + arguments.length;
}
}
}
var myFunc = force(function(foo, bar, baz) {
// ...
});
In general this sounds like a bad idea, because you’re basically messing with the language. Do you really forget to pass arguments that often?
You could use the decorator pattern. The following decorator allows you to specify minimum and maximum number of arguments that need to be passed and an optional error handler.
/* Wrap the function *f*, so that *error_callback* is called when the number
of passed arguments is not with range *nmin* to *nmax*. *error_callback*
may be ommited to make the wrapper just throw an error message.
The wrapped function is returned. */
function require_arguments(f, nmin, nmax, error_callback) {
if (!error_callback) {
error_callback = function(n, nmin, nmax) {
throw 'Expected arguments from ' + nmin + ' to ' + nmax + ' (' +
n + ' passed).';
}
}
function wrapper() {
var n_args = arguments.length;
console.log(n_args, nmin, nmax);
console.log((nmin <= 0) && (0 <= nmax));
if ((nmin <= n_args) && (n_args <= nmax)) {
return f.apply(this, arguments);
}
return error_callback(n_args, nmin, nmax);
}
for (e in f) {
wrapper[e] = f[e];
}
return wrapper;
}
var foo = require_arguments(function(a, b, c) {
/* .. */
}, 1, 3);
foo(1);
foo(1, 2);
foo(1, 2, 3);
foo(1, 2, 3, 4); // uncaught exception: Expected arguments from 1 to 3 (4 passed).
foo(); // uncaught exception: Expected arguments from 1 to 3 (0 passed).

jQuery/Javascript: How can I evaluate the validity of function arguments efficiently with a range of valid types?

I've got a rather large plugin that I am currently writing in jQuery which is using a lot of internal functions that can accept varying arguments depending on the function.
I caught myself constantly writing the following in every function to stop the code from running if an argument hasn't been supplied or isn't valid:
add : function(args) {
if (args===undefined) return;
// function code;
},...
I was hoping that in a DRY type of sense it would be a good idea to write a little internal helper function that would do this for me.
Is this actually a good idea and most importantly what is the best/secure way to check for a varied range of acceptable arguments?
There are a lot of functions with multiple arguments in this plugin, for example:
load : function( filename , path , excludeFromRandom , callback ) {}
where filename is a string,
path is a string,
excludeFromRandom is a boolean and
callback can be a function or a string.
What is a good way to check for the existence and validity of these types of arguments without rewriting the same code over and over?
Any suggestions and ideas would be great.
Thanks for reading.
It depends to what extent you want to do this. In idea would be to create a validation function which takes a argument -> rule mapping. E.g.:
function foo(somestring, somenumber) {
var rules = {
'somestring': Validator.rules.isString,
'somenumber': Validator.rules.inRange(5,10);
};
}
Validator would contain the basic logic and some helper functions (rules):
var Validator = {
valid: function(args, rules) {
for(var name in rules) {
if(!rules[name](args[name])) {
return false;
}
}
return true;
},
rules: {
isString: function(arg) {
return (typeof arg === 'string');
},
inRange: function(x,y) {
return function(arg) {
return !isNaN(+arg) && x <= arg && arg <= y;
}
}
}
}
This is just a sketch, it certainly can be extended (like accepting multiple rules per argument), but it should give you some idea.
That said, you don't have to check every argument. Provide decent documentation. If people use your plugin in a wrong way, i.e. passing wrong argument types, then your code will throw an error anyway.
Update:
If want to do this very often, then a good idea is to write a wrapper function and you just pass the function and the rules to it:
function ensure(func, rules, context) {
context = context || this;
return function() {
if(Validator.valid(arguments, rules)) {
return func.apply(context, arguments);
}
return null; // or throw error, whatever you want
}
}
Then you can define your function normally as:
var foo = function(somestring, somenumber) {
// ...
};
and just add validation to it:
var rules = {...};
foo = ensure(foo, rules);
You could even consider to make ensure accept a callback which gets called on error or success of the function, instead of returning a value. There are a lot of possibilities.

Handling optional parameters in javascript

I have a static javascript function that can take 1, 2 or 3 parameters:
function getData(id, parameters, callback) //parameters (associative array) and callback (function) are optional
I know I can always test if a given parameter is undefined, but how would I know if what was passed was the parameter or the callback?
What's the best way of doing this?
Examples of what could be passed in:
1:
getData('offers');
2:
var array = new Array();
array['type']='lalal';
getData('offers',array);
3:
var foo = function (){...}
getData('offers',foo);
4:
getData('offers',array,foo);
You can know how many arguments were passed to your function and you can check if your second argument is a function or not:
function getData (id, parameters, callback) {
if (arguments.length == 2) { // if only two arguments were supplied
if (Object.prototype.toString.call(parameters) == "[object Function]") {
callback = parameters;
}
}
//...
}
You can also use the arguments object in this way:
function getData (/*id, parameters, callback*/) {
var id = arguments[0], parameters, callback;
if (arguments.length == 2) { // only two arguments supplied
if (Object.prototype.toString.call(arguments[1]) == "[object Function]") {
callback = arguments[1]; // if is a function, set as 'callback'
} else {
parameters = arguments[1]; // if not a function, set as 'parameters'
}
} else if (arguments.length == 3) { // three arguments supplied
parameters = arguments[1];
callback = arguments[2];
}
//...
}
If you are interested, give a look to this article by John Resig, about a technique to simulate method overloading on JavaScript.
Er - that would imply that you are invoking your function with arguments which aren't in the proper order... which I would not recommend.
I would recommend instead feeding an object to your function like so:
function getData( props ) {
props = props || {};
props.params = props.params || {};
props.id = props.id || 1;
props.callback = props.callback || function(){};
alert( props.callback )
};
getData( {
id: 3,
callback: function(){ alert('hi'); }
} );
Benefits:
you don't have to account for argument order
you don't have to do type checking
it's easier to define default values because no type checking is necessary
less headaches. imagine if you added a fourth argument, you'd have to update your type checking every single time, and what if the fourth or consecutive are also functions?
Drawbacks:
time to refactor code
If you have no choice, you could use a function to detect whether an object is indeed a function ( see last example ).
Note: This is the proper way to detect a function:
function isFunction(obj) {
return Object.prototype.toString.call(obj) === "[object Function]";
}
isFunction( function(){} )
You should check type of received parameters. Maybe you should use arguments array since second parameter can sometimes be 'parameters' and sometimes 'callback' and naming it parameters might be misleading.
I know this is a pretty old question, but I dealt with this recently. Let me know what you think of this solution.
I created a utility that lets me strongly type arguments and let them be optional. You basically wrap your function in a proxy. If you skip an argument, it's undefined. It may get quirky if you have multiple optional arguments with the same type right next to each other. (There are options to pass functions instead of types to do custom argument checks, as well as specifying default values for each parameter.)
This is what the implementation looks like:
function displayOverlay(/*message, timeout, callback*/) {
return arrangeArgs(arguments, String, Number, Function,
function(message, timeout, callback) {
/* ... your code ... */
});
};
For clarity, here is what is going on:
function displayOverlay(/*message, timeout, callback*/) {
//arrangeArgs is the proxy
return arrangeArgs(
//first pass in the original arguments
arguments,
//then pass in the type for each argument
String, Number, Function,
//lastly, pass in your function and the proxy will do the rest!
function(message, timeout, callback) {
//debug output of each argument to verify it's working
console.log("message", message, "timeout", timeout, "callback", callback);
/* ... your code ... */
}
);
};
You can view the arrangeArgs proxy code in my GitHub repository here:
https://github.com/joelvh/Sysmo.js/blob/master/sysmo.js
Here is the utility function with some comments copied from the repository:
/*
****** Overview ******
*
* Strongly type a function's arguments to allow for any arguments to be optional.
*
* Other resources:
* http://ejohn.org/blog/javascript-method-overloading/
*
****** Example implementation ******
*
* //all args are optional... will display overlay with default settings
* var displayOverlay = function() {
* return Sysmo.optionalArgs(arguments,
* String, [Number, false, 0], Function,
* function(message, timeout, callback) {
* var overlay = new Overlay(message);
* overlay.timeout = timeout;
* overlay.display({onDisplayed: callback});
* });
* }
*
****** Example function call ******
*
* //the window.alert() function is the callback, message and timeout are not defined.
* displayOverlay(alert);
*
* //displays the overlay after 500 miliseconds, then alerts... message is not defined.
* displayOverlay(500, alert);
*
****** Setup ******
*
* arguments = the original arguments to the function defined in your javascript API.
* config = describe the argument type
* - Class - specify the type (e.g. String, Number, Function, Array)
* - [Class/function, boolean, default] - pass an array where the first value is a class or a function...
* The "boolean" indicates if the first value should be treated as a function.
* The "default" is an optional default value to use instead of undefined.
*
*/
arrangeArgs: function (/* arguments, config1 [, config2] , callback */) {
//config format: [String, false, ''], [Number, false, 0], [Function, false, function(){}]
//config doesn't need a default value.
//config can also be classes instead of an array if not required and no default value.
var configs = Sysmo.makeArray(arguments),
values = Sysmo.makeArray(configs.shift()),
callback = configs.pop(),
args = [],
done = function() {
//add the proper number of arguments before adding remaining values
if (!args.length) {
args = Array(configs.length);
}
//fire callback with args and remaining values concatenated
return callback.apply(null, args.concat(values));
};
//if there are not values to process, just fire callback
if (!values.length) {
return done();
}
//loop through configs to create more easily readable objects
for (var i = 0; i < configs.length; i++) {
var config = configs[i];
//make sure there's a value
if (values.length) {
//type or validator function
var fn = config[0] || config,
//if config[1] is true, use fn as validator,
//otherwise create a validator from a closure to preserve fn for later use
validate = (config[1]) ? fn : function(value) {
return value.constructor === fn;
};
//see if arg value matches config
if (validate(values[0])) {
args.push(values.shift());
continue;
}
}
//add a default value if there is no value in the original args
//or if the type didn't match
args.push(config[2]);
}
return done();
}
I recommend you to use ArgueJS.
You can just type your function this way:
function getData(){
arguments = __({id: String, parameters: [Object], callback: [Function]})
// and now access your arguments by arguments.id,
// arguments.parameters and arguments.callback
}
I considered by your examples that you want your id parameter to be a string, right?
Now, getData is requiring a String id and is accepting the optionals Object parameters and Function callback. All the use cases you posted will work as expected.
So use the typeof operator to determine if the second parameter is an Array or function.
This can give some suggestions:
https://planetpdf.com/testing-for-object-types-in-javascript/
I am not certain if this is work or homework, so I don't want to give you the answer at the moment, but the typeof will help you determine it.
Are you saying you can have calls like these:
getData(id, parameters);
getData(id, callback)?
In this case you can't obviously rely on position and you have to rely on analysing the type:
getType() and then if necessary getTypeName()
Check if the parameter in question is an array or a function.
You can use the arguments object property inside the function.
I think you want to use typeof() here:
function f(id, parameters, callback) {
console.log(typeof(parameters)+" "+typeof(callback));
}
f("hi", {"a":"boo"}, f); //prints "object function"
f("hi", f, {"a":"boo"}); //prints "function object"
If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
use this approach. The idea is simple - use literal objects to combine your parameters:
function getData(id, opt){
var data = voodooMagic(id, opt.parameters);
if (opt.callback!=undefined)
opt.callback.call(data);
return data;
}
getData(5, {parameters: "1,2,3", callback:
function(){for (i=0;i<=1;i--)alert("FAIL!");}
});
This I guess may be self explanatory example:
function clickOn(elem /*bubble, cancelable*/) {
var bubble = (arguments.length > 1) ? arguments[1] : true;
var cancelable = (arguments.length == 3) ? arguments[2] : true;
var cle = document.createEvent("MouseEvent");
cle.initEvent("click", bubble, cancelable);
elem.dispatchEvent(cle);
}
Can you override the function? Will this not work:
function doSomething(id){}
function doSomething(id,parameters){}
function doSomething(id,parameters,callback){}

Categories

Resources