Keyword arguments for Javascript. Similar to python's kwargs
This little tool gives you the ability to use keyword arguments support for your functions. So you can either specify each argument as you wish or use the arguments regularly. In fact you can do both at the same time.
Another feature is to have the ability to set default values for your function arguments without changing or adding any code to your function.
Usage
Just include the script on your site. That's it. When included it will add a new method called kwargs
to Function prototype and you can use it like this:
var { // code};
Examples
Just write your function as you would normally, and don't worry about the arguments size. just call .kwargs()
and rest will be handled.
var { // Your code};
Now, if you want you can pass all arguments in a single object and they all will be mapped to their correct places
;
You can also use your function like you would normally use
;
the best part is that you can do both
;
Using Default values for arguments
Let's say we have this function that says Hello to a given name.
var { return "Hello " + name;};; // -> Hello Frank
If no name is given, we want it to return "Hello World", usually you would have to add conditions to your function and check for existence of name
argument. kwargs automatically handles that for you.
var { return "Hello " + name;}; // Set a default value for your argument and // it will be used when this argument is empty// Here are the results; // -> Hello Frank; // -> Hello World
A real example
Let's say we have a function that receives a lot of arguments and generates a name with prefixes and suffixes when provided.
var { var name = ; ifprefix name; name; ifmiddleName name; name; ifsuffix name; return name;};
Now, when we want create a name with only a suffix, all we have to do is to provide the name and suffix. You can only pass required arguments without changing anything on your function code.
;// -> John Doe Ph.D.// -> Staff Sgt. Max Fightmaster;// -> Sir Isaac Newton PRS MP
Important Note
If last argument passed is an object, code assumes it's a kwargs
object, if your function accepts objects as arguments
you should be careful about this, here is an example.
// in both cases, `anObject` argument will be interpreted as `kwargs` object and be ignored;;
to avoid this problem you have two solutions
; // passing last argument as an empty object// or using the options method and passing your object in kwargs;
LICENSE
MIT License