Last active
August 29, 2015 14:01
-
-
Save mlconnor/bafb577e1250ba7e1376 to your computer and use it in GitHub Desktop.
String based pick mixins for underscore
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
_.mixin({ | |
pickStartsWith : function(obj,beginStr) { | |
if ( _.isArray(obj) || ! _.isObject(obj) ) throw new TypeError("pickStartsWith must be called on an object"); | |
return _.pick(obj, _.filter(_.keys(obj), function(el, index) { return el.indexOf(beginStr) == 0; })); | |
}, | |
pickMatch : function(obj,regex) { | |
if ( _.isArray(obj) || ! _.isObject(obj) ) throw new TypeError("pickBeginsWith must be called on an object"); | |
return _.pick(obj, _.filter(_.keys(obj), function(el, index) { return el.match(regex) != null; })); | |
}, | |
keyReplace : function(obj,regex, replace) { | |
if ( _.isArray(obj) || ! _.isObject(obj) ) throw new TypeError("pickReplace must be called on an object found " + obj); | |
console.log("a1=" + obj + " a2=" + regex + " a3=" + replace); | |
var newObj = {}; | |
_.each(obj, function(val, key) { newObj[key.replace(regex,replace)] = val; }); | |
return newObj; | |
}, | |
eachFn : function() { | |
var eachArgs = arguments; | |
var newArr = new Array(); | |
if ( ! _.isArray(arguments[0]) ) throw new TypeError("eachFn must be called on an array"); | |
if ( ! _.isFunction(arguments[1]) ) throw new TypeError("eachFn must be given an array as second parameter"); | |
_.each(arguments[0], function(val, index) { | |
var fnArgs = Array.prototype.slice.call(eachArgs,2); | |
fnArgs.unshift(val); | |
newArr.push(eachArgs[1].apply(val,fnArgs)); | |
}); | |
return newArr; | |
}, | |
eachFnThis : function() { | |
var eachArgs = arguments; | |
var newArr = new Array(); | |
if ( ! _.isArray(arguments[0]) ) throw new TypeError("eachFn must be called on an array"); | |
if ( ! _.isFunction(arguments[1]) ) throw new TypeError("eachFn must be given an array as second parameter"); | |
_.each(arguments[0], function(val, index) { | |
var fnArgs = Array.prototype.slice.call(eachArgs,2); | |
newArr.push(eachArgs[1].apply(val,fnArgs)); | |
}); | |
return newArr; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment