Skip to content

Instantly share code, notes, and snippets.

@marlun78
Last active October 6, 2015 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlun78/2964814 to your computer and use it in GitHub Desktop.
Save marlun78/2964814 to your computer and use it in GitHub Desktop.
Adds default param values to a function
/**
* Default Arguments
* Copyright (c) 2012, marlun78
* MIT License, https://gist.github.com/marlun78/bd0800cf5e8053ba9f83
*
* Set default arguments to a function
* @param {function} fn - The function to decorate
* @param {*} [args...] - Any default arguments
* @returns {function} - The new decorated function
*
* @example
* var decorated = setDefaultArguments(function add(a, b) {
* return a + b;
* }, 2, 2);
* decorated(); //> 4
* decorated(1); //> 3
* decorated(undefined, 0); //> 2
*/
var setDefaultArguments = (function (undefined) {
var arraySlice = Array.prototype.slice;
function mask(left, right) {
var max = Math.max(left.length, right.length);
for (var index = 0; index < max; index++) {
left[index] = left[index] === undefined ? right[index] : left[index];
}
return left;
}
return function (fn/* [, defaultArgs...] */) {
var defaults = arraySlice.call(arguments, 1);
if (typeof fn !== 'function') {
throw new TypeError;
}
return function () {
return fn.apply(this, mask(arraySlice.call(arguments), defaults));
};
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment