Last active
October 6, 2015 08:27
-
-
Save marlun78/2964814 to your computer and use it in GitHub Desktop.
Adds default param values to a function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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