Last active
August 29, 2015 14:00
-
-
Save barneycarroll/3cd2410bef8b2e821e2a to your computer and use it in GitHub Desktop.
returner is a convenience function that allows you to invoke mutator methods on arrays (or anything else) and return the mutated array itself rather than some arbitrary property of that array.
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
// returner is a convenience function that allows you to invoke mutator methods on arrays (or anything else) | |
// and return the mutated array itself rather than some arbitrary property of that array. | |
// | |
// Why? | |
// I have never been convenienced by the returned length of an array after pushing to it. | |
// I have often wanted to push to an array and return it with the same statement. | |
// | |
// Seriously? Like, when? | |
// Can I use a word in its own definition? At line 27, I want to modify an array and return it. | |
// Thanks to returner, I'm evaluating that as a function argument expression. | |
// Without it, I'd have to modify it in a separate line, then pass it as an argument. | |
// | |
// Usage: | |
// returner( [ 1, 2 ], 'push', 3 ); // -> [ 1, 2, 3 ] | |
// returner( [ 1, 2, 3], 'splice', 1, 1, 0 ); // -> [ 1, 0, 3 ] | |
// | |
// Allows chaining of native object & array mutator methods via chain method: | |
// returner.chain( [ 5, 6, 7 ] )( 'unshift', 4 )( 'splice', 2, 2, 5 ).value(); // -> [ 4, 5, 5 ] | |
function returner( obj, method ){ | |
obj[ method ].apply( obj, Array.prototype.slice.call( arguments, 2 ) ); | |
return obj; | |
} | |
returner.chain = function wrap( obj ){ | |
function chainReturner(){ | |
returner.apply( undefined, returner( Array.prototype.slice.call( arguments ), 'unshift', obj) ); | |
return chainReturner; | |
} | |
chainReturner.value = function unWrap(){ | |
return obj; | |
}; | |
return chainReturner; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment