Skip to content

Instantly share code, notes, and snippets.

@lewisje
Forked from SeanJM/fnChain.js
Last active February 22, 2016 04:23
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 lewisje/041f4d25d12c8a135a8b to your computer and use it in GitHub Desktop.
Save lewisje/041f4d25d12c8a135a8b to your computer and use it in GitHub Desktop.
A function which allows the augmentation of an Object with functional methods.
// 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