Skip to content

Instantly share code, notes, and snippets.

@cmmartin
Last active August 29, 2015 14:13
Show Gist options
  • Save cmmartin/6be43d6218f7ee027c90 to your computer and use it in GitHub Desktop.
Save cmmartin/6be43d6218f7ee027c90 to your computer and use it in GitHub Desktop.
My collection of Underscore.js mixins
_.mixin({
// _.contains for strings with optional case sensitivity
hasSubstring: function (stringA, stringB, caseSensitive) {
if (caseSensitive) return stringA.indexOf(stringB) >= 0;
return stringA.toLowerCase().indexOf(stringB.toLowerCase()) >= 0;
},
// Get the difference between two arrays - shallow only
diffArrays: function (a, b) {
// 1) Get the list of all unique values from both arrays (_.union)
// 2) Reject any of the unique values that are present in both arrays (leaving the diff)
return _(a).chain().union(b).reject(valueIsInBothArrays).value();
function valueIsInBothArrays(value) {
return _(a).indexOf(value) >= 0 && _(b).indexOf(value) >= 0;
}
},
// Sum the numeric values of an array
sum: function (arr) {
return _(arr).reduce(function (sum, value) {
return sum += value;
}, 0);
},
// Just like _.tap, except returns the result of the interceptor instead of obj
zap: function (obj, interceptor) {
return interceptor(obj);
},
// Linear interpolation - t should be between 0 and 1
lerp: function (t, min, max) {
return min + (max - min) * t;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment