Design & Download
Your JS Library
in Seconds!!!

Snippet: param()

Written by Christopher West (cwest) on November 13, 2015.
Essentially allows values to be passed to a function by name. Also provides the ability to set default values.
function param(callback, arrFields) {
  for (var t, defaults = [], len = arrFields.length, i = len; i--;) {
    t = toArray(arrFields[i]);
    if (1 in t) {
      defaults[i] = t[1];
    }
    arrFields[i] = t[0];
  }

  return function(fields) {
    fields = Object(fields);
    for (var t, args = slice(arguments, 0), i = len; i--;) {
      args.unshift(fields && (has(fields, t=arrFields[i]) || !has(defaults, i) ? fields[t] : defaults[i]));
    }
    return callback.apply(this, args);
  };
}

One thing that we can't do in JavaScript is pass arguments by name, but with param(...) we can:

var sayWhoYouAre = YourJS.param(
  ['firstName', 'lastName', 'age'],
  function(firstName, lastName, age) {
    alert('Your name is ' + firstName + ' ' + lastName + ' and you are ' + age + ' year' + (age - 1 ? 's' : '') + ' old.');
  }
);

In order to call the above function while passing the arguments by name we can do the following:

sayWhoYouAre({
  firstName: 'Chris',
  lastName: 'West',
  age: 25
});

param(...) API Documentation

Parameters

  1. callback {Function}:
    The function which is called with the modified arguments passed in.
  2. arrFields {Array}:
    An array indicating the key where to get the argument values at the corresponding indices. Each array item can either be a string (key) or an array where the first item is a string (key) and the second is the default value.

Returns

Returns a wrapper function which when called will pass in the arguments as specified by arrFields using the first argument as the basis for the keys specified.