Skip to content

Instantly share code, notes, and snippets.

_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]
// 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
// 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
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);
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"
@acrosa
acrosa / oauth-monkey-patch.rb
Created December 13, 2010 12:20
OAuth gem workaround on JRuby
module OAuth::Signature::HMAC
class Base < OAuth::Signature::Base
private
def digest
self.class.digest_class Object.module_eval("::Digest::#{self.class.digest_klass}")
digest = OpenSSL::Digest::Digest.new('sha1')
OpenSSL::HMAC.digest(digest, secret, signature_base_string)
end
end
end
@acrosa
acrosa / earlyflushing.rb
Created January 25, 2011 00:40
early flush
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'lib/rack_patch'
# this get's executed for all actions
before do
content_type :html, 'charset' => 'utf-8'
end
@acrosa
acrosa / rack_patch.rb
Created January 25, 2011 00:47
required for doing early flush on JRuby under Tomcat
class JRuby::Rack::Response
def write_body(response)
stream = response.getOutputStream
begin
@body.each do |el|
stream.write(el.to_java_bytes)
stream.flush
end
rescue LocalJumpError => e
# HACK: deal with objects that don't comply with Rack specification
$ curl 'http://localhost:8083/earlyflush/crazy' -i
HTTP/1.1 200 OK
Date: Fri, 28 Jan 2011 21:23:07 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Server: Jetty(6.1.22)
Here’s to the crazy ones. The misfits. The rebels. The troublemakers. The round pegs in the square holes.
The ones who see things differently. They’re not fond of rules. And they have no respect for the status quo. You can quote them, disagree with them, glorify or vilify them.
About the only thing you can’t do is ignore them. Because they change things. They invent. They imagine. They heal. They explore. They create. They inspire. They push the human race forward.