Skip to content

Instantly share code, notes, and snippets.

var obj1 = { name: "Alejandro" }
var obj2 = { last: "Crosa", sayName: function (){ return this.name +" "+ this.last; } }
_.extend(obj1, obj2) // Extend obj1 with obj2's properties and methods
obj1.sayName()
=> "Alejandro Crosa"
var capitalize = function(text){
return text[0].toUpperCase() + text.substring(1, text.length);
}
var buildHtml = function(phrase){
return "<h1>"+ phrase +"</h1>";
}
// We compose the preceding functions into a new one
var buildTitle = _.compose(capitalize, buildHtml);
// Given an Object and a function
var obj = { name: "Alejandro" };
var func = function(message) { return message +" "+ this.name; };
var f = _.bind(func, obj); // Bind it!
f("Hello there")
=> "Hello there Alejandro"
// If you pass a third argument you can pre fill the arguments of the function
// Procedural style
var selected = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
var max = _.max(selected);
=> 6
// Chain methods together
_([1, 2, 3, 4, 5, 6]).chain().select(function(num) { return num % 2 == 0 }).max().value()
=> 6
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]
_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]