-
-
Save lewisje/041f4d25d12c8a135a8b to your computer and use it in GitHub Desktop.
A function which allows the augmentation of an Object with functional methods.
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
// Here is a JSFiddle with a concrete example: https://jsfiddle.net/SeanJM/rg3ftcgk/1/ | |
// This is one of Sean's most leveraged functions, which he uses to keep my code nice and modular | |
function fnChain(target, source, args) { | |
'use strict'; | |
var objProto = Object.prototype, hasOwn, chain, k; | |
if (objProto.toString.apply(args) !== '[object Array]') { | |
throw new TypeError('Invalid argument for "fnChain": The 3rd argument must be an array of arguments.'); | |
} | |
hasOwn = objProto.hasOwnProperty; | |
chain = function chain(k) { | |
function chainApply() { | |
var len = arguments.length, aArgs = new Array(len), i, b; | |
for (i = 0; i < len; i++) { // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments | |
aArgs[i] = arguments[i]; | |
} | |
b = source[k].apply(null, args.concat(aArgs)); | |
return typeof b === 'undefined' ? target : b; | |
} | |
return chainApply; | |
}; | |
for (k in source) { | |
if (typeof source[k] === 'function' && !(k in target) && hasOwn.call(source, k)) { | |
target[k] = chain(k); | |
} | |
} | |
return target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment