- Source:
Methods
kwargs(func, defaultsopt, nullable) → {function}
This function creates a function where we can set all parameters as a config object by name for each call, while also allowing to set default values for parameters on function creation.
This is heavily inspired by Python's way of handling parameters, therefore the name.
This enables you to overload complex function signatures with tailor-fit version for your use cases and to call functions with specific parameter sets in a very readable way, without adding empty values to the list of parameters. So you just define what you want to set and those parts are clearly named.
Each parameter you pass to the created kwargs function may be one of two variants:
- either it is not a plain object; in that case the parameter is passed to the original function as is at the position the parameter is declared in the call
- or the parameter is a plain object, in which case we treat the parameter as kwargs and try to match keys to parameters; in case you ever have to pass a plain object as-is: setting "kwargs: false" in the object tells the parser to skip matching props to parameters
You can even mix these types. If two parameters describe the same value in the call, the last declaration wins.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
func |
function | the function to provide kwargs to |
||
defaults |
Object |
<optional> <nullable> |
null | the default kwargs to apply to func, essentially setting default values for all given keys fitting parameters of the function |
- Source:
Throws:
error if func is not a function or parameter names of func could not be identified
Returns:
- Type
- function
Example
const fTest = function(tick, trick, track){ console.log(tick, trick, track); };
const fKwargsTest = kwargs(fTest, {track : 'defaultTrack'});
fKwargsTest({tick : 'tiick', trick : 'trick'});
=> "tiick, trick, defaultTrack"
kwargs(fTest, {track : 'defaultTrack'})('argumentTick', {trick : 'triick', track : 'trACK'});
=> "argumentTick, triick, trACK"
kwargs(fTest, {track : 'defaultTrack'})('argumentTick', {trick : 'triick', track : 'track'}, 'trackkkk');
=> "argumentTick, triick, trackkkk"