Skip to content

Instantly share code, notes, and snippets.

@gpawlik
Last active March 5, 2016 20:07
Show Gist options
  • Save gpawlik/239f9f8515fbcf5a0c0f to your computer and use it in GitHub Desktop.
Save gpawlik/239f9f8515fbcf5a0c0f to your computer and use it in GitHub Desktop.
Shorthand for Underscore.js functions
// Array Functions
var arr1 = ['ted', 'bernie', 'hillary', 'marco', 'donald'];
console.log('first:', _.first(arr1));
console.log('last:', _.last(arr1));
console.log('initial:', _.initial(arr1));
console.log('rest:', _.rest(arr1));
var arr2 = [1, 2, 3, [4, 4.5, 4.75], 5, false, 7];
console.log('compact:', _.compact(arr2));
console.log('flatten:', _.flatten(arr2));
var arr3a = ['ted', 'hillary'];
var arr3b = ['bernie', 'marco', 'ted', 'donald', 'marco'];
console.log('without:', _.without(arr3a, 'ted'));
console.log('intersection:', _.intersection(arr3a, arr3b));
console.log('union:', _.union(arr3a, arr3b));
console.log('difference:',_.difference(arr3a, arr3b));
console.log('uniq:', _.uniq(arr3b));
console.log('indexOf:', _.indexOf(arr3b, 'marco'));
console.log('lastIndexOf:', _.lastIndexOf(arr3b, 'marco'));
console.log('zip:', _.zip(arr1, arr3a, arr3b));
console.log('range:', _.range(2, 10));
// Collections Functions
// Note: Collection functions work on arrays, objects, and array-like objects such as arguments, NodeList and similar. But it works by duck-typing, so avoid passing objects with a numeric length property.
// _.each(list, iteratee, [context]) Alias: forEach
_.each([1, 2, 3], console.log);
// alerts each number in turn...
_.each({one: 1, two: 2, three: 3}, console.log);
// alerts each number value in turn...
// _.map(list, iteratee, [context]) Alias: collect
_.map([1, 2, 3], function(num){ return num * 3; });
// [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
// [3, 6, 9]
_.map([[1, 2], [3, 4]], _.first);
// [1, 3]
// _.reduce(list, iteratee, [memo], [context]) Aliases: inject, foldl
var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
// 6
// _.reduceRight(list, iteratee, memo, [context]) Alias: foldr
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
// [4, 5, 2, 3, 0, 1]
// _.find(list, predicate, [context]) Alias: detect
var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
// 2
// _.filter(list, predicate, [context]) Alias: select
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
// [2, 4, 6]
// _.where(list, properties)
var listOfPlays = [{title: "Cymbeline", author: "Shakespeare", year: 1611},
{title: "The Tempest", author: "Shakespeare", year: 1611},
{title: "Romeo & Juliet", author: "Shakespeare", year: 1620}]
_.where(listOfPlays, {author: "Shakespeare", year: 1611});
// [{title: "Cymbeline", author: "Shakespeare", year: 1611},
// {title: "The Tempest", author: "Shakespeare", year: 1611}]
// _.findWhere(list, properties)
var publicServicePulitzers = [];
_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});
// {year: 1918, newsroom: "The New York Times",
// reason: "For its public service in publishing in full so many official reports,
// documents and speeches by European statesmen relating to the progress and
// conduct of the war."}
// _.reject(list, predicate, [context])
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
// [1, 3, 5]
// _.every(list, [predicate], [context]) Alias: all
_.every([true, 1, null, 'yes'], _.identity);
// false
// _.some(list, [predicate], [context]) Alias: any
_.some([null, 0, 'yes', false]);
// true
// _.contains(list, value, [fromIndex]) Alias: includes
_.contains([1, 2, 3], 3);
// true
// _.invoke(list, methodName, *arguments)
_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
// [[1, 5, 7], [1, 2, 3]]
// _.pluck(list, propertyName)
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
// ["moe", "larry", "curly"]
// _.max(list, [iteratee], [context])
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.max(stooges, function(stooge){ return stooge.age; });
// {name: 'curly', age: 60};
// _.min(list, [iteratee], [context])
var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
// 2
// _.sortBy(list, iteratee, [context])
_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
// [5, 4, 6, 3, 1, 2]
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');
// [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];
// _.groupBy(list, iteratee, [context])
_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
// {1: [1.3], 2: [2.1, 2.4]}
_.groupBy(['one', 'two', 'three'], 'length');
// {3: ["one", "two"], 5: ["three"]}
// _.indexBy(list, iteratee, [context])
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.indexBy(stooges, 'age');
// {
// "40": {name: 'moe', age: 40},
// "50": {name: 'larry', age: 50},
// "60": {name: 'curly', age: 60}
//}
//_.countBy(list, iteratee, [context])
_.countBy([1, 2, 3, 4, 5], function(num) {
return num % 2 == 0 ? 'even': 'odd';
});
// {odd: 3, even: 2}
//_.shuffle(list)
_.shuffle([1, 2, 3, 4, 5, 6]);
// [4, 1, 6, 3, 5, 2]
//_.sample(list, [n])
_.sample([1, 2, 3, 4, 5, 6]);
// 4
_.sample([1, 2, 3, 4, 5, 6], 3);
// [1, 6, 2]
// _.toArray(list)
(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
// [2, 3, 4]
// _.size(list)
_.size({one: 1, two: 2, three: 3});
// 3
// _.partition(array, predicate)
_.partition([0, 1, 2, 3, 4, 5], _.isOdd);
// [[1, 3, 5], [0, 2, 4]]
// Objects Functions
// _.keys(object)
_.keys({one: 1, two: 2, three: 3});
// ["one", "two", "three"]
// _.allKeys(object)
function Stooge(name) {
this.name = name;
}
Stooge.prototype.silly = true;
_.allKeys(new Stooge("Moe"));
// ["name", "silly"]
// _.values(object)
_.values({one: 1, two: 2, three: 3});
// [1, 2, 3]
// _.mapObject(object, iteratee, [context])
_.mapObject({start: 5, end: 12}, function(val, key) {
return val + 5;
});
// {start: 10, end: 17}
// _.pairs(object)
_.pairs({one: 1, two: 2, three: 3});
// [["one", 1], ["two", 2], ["three", 3]]
// _.invert(object)
_.invert({Moe: "Moses", Larry: "Louis", Curly: "Jerome"});
// {Moses: "Moe", Louis: "Larry", Jerome: "Curly"};
// _.create(prototype, props)
var moe = _.create(Stooge.prototype, {name: "Moe"});
// _.functions(object) Alias: methods
_.functions(_);
// ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...
// _.findKey(object, predicate, [context])
// _.extend(destination, *sources)
_.extend({name: 'moe'}, {age: 50});
// {name: 'moe', age: 50}
// _.extendOwn(destination, *sources) Alias: assign
// Like extend, but only copies own properties over to the destination object.
//_.pick(object, *keys)
_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
// {name: 'moe', age: 50}
_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
return _.isNumber(value);
});
// {age: 50}
// _.omit(object, *keys)
_.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');
// {name: 'moe', age: 50}
_.omit({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
return _.isNumber(value);
});
// {name: 'moe', userid: 'moe1'}
// _.defaults(object, *defaults)
var iceCream = {flavor: "chocolate"};
_.defaults(iceCream, {flavor: "vanilla", sprinkles: "lots"});
// {flavor: "chocolate", sprinkles: "lots"}
// _.clone(object)
_.clone({name: 'moe'});
// {name: 'moe'};
// _.tap(object, interceptor)
_.chain([1,2,3,200])
.filter(function(num) { return num % 2 == 0; })
.tap(alert)
.map(function(num) { return num * num })
.value();
// // [2, 200] (alerted)
// [4, 40000]
// _.has(object, key)
_.has({a: 1, b: 2, c: 3}, "b");
// true
// _.property(key)
var stooge = {name: 'moe'};
'moe' === _.property('name')(stooge);
// true
// _.propertyOf(object)
var stooge = {name: 'moe'};
_.propertyOf(stooge)('name');
// 'moe'
// _.matcher(attrs) Alias: matches
var ready = _.matcher({selected: true, visible: true});
var readyToGoList = _.filter(list, ready);
// _.isEqual(object, other)
var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};
var clone = {name: 'moe', luckyNumbers: [13, 27, 34]};
stooge == clone;
// false
_.isEqual(stooge, clone);
// true
// _.isMatch(object, properties)
var stooge = {name: 'moe', age: 32};
_.isMatch(stooge, {age: 32});
// true
// _.isEmpty(object)
_.isEmpty([1, 2, 3]);
// false
_.isEmpty({});
// true
// _.isElement(object)
_.isElement(jQuery('body')[0]);
// true
// _.isArray(object)
(function(){ return _.isArray(arguments); })();
// false
_.isArray([1,2,3]);
// true
// _.isObject(value)
_.isObject({});
// true
_.isObject(1);
// false
// _.isArguments(object)
(function(){ return _.isArguments(arguments); })(1, 2, 3);
// true
_.isArguments([1,2,3]);
// false
// _.isFunction(object)
_.isFunction(alert);
// true
// _.isString(object)
_.isString("moe");
// true
// _.isNumber(object)
_.isNumber(8.4 * 5);
// true
// _.isFinite(object)
_.isFinite(-101);
// true
_.isFinite(-Infinity);
// false
// _.isBoolean(object)
_.isBoolean(null);
// false
// _.isDate(object)
_.isDate(new Date());
// true
// _.isRegExp(object)
_.isRegExp(/moe/);
// true
// _.isError(object)
try {
throw new TypeError("Example");
} catch (o_O) {
_.isError(o_O)
}
// true
// _.isNaN(object)
_.isNaN(NaN);
// true
isNaN(undefined);
// true
_.isNaN(undefined);
// false
// _.isNull(object)
_.isNull(null);
// true
_.isNull(undefined);
// false
// _.isUndefined(value)
_.isUndefined(window.missingVariable);
// true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment