Skip to content

Instantly share code, notes, and snippets.

View balanza's full-sized avatar

Emanuele De Cupis balanza

View GitHub Profile
var obj = ['mario', 'luigi'];
var lambda = function(elem){
alert('Thanks ' + elem + ' but the princess is in another castle');
};
_.each(obj, lambda);
_.chain(obj)
.map(function(e){
//my mapping operation
})
.reduce(function(m, e){
//my reducing operation
})
.filter(function(e){
//guess what?
})
//those two instructions are equivalent
_.map(myArray, function(e){});
_(myArray).map(function(e){});
//this is row data coming from db
var dataset = [{
firstname: 'John',
lastname: 'Doe',
birth: '1986-02-09',
languages: ['en'],
sex: 'm'
}, {
firstname: 'Maria',
lastname: 'Rossi',
//click count
var count = 0;
//this is the handler
var onClick = function(e){
alert('button clicked ' + (++count) + ' times');
};
//this is the "throttled" function,
// that is a function that executes only once in a given timespan (here: 200ms)
//this is the handler
var onClick = function(e){
alert('button clicked just one time');
};
//this is the "once" function,
// that is a function that executes only once, forever
var onlyOnce = _.once(onClick);
//here the handler is bound to the event
//the buffer to store measures
var buffer = [];
//this is the function that calls the endpont
var saveToAPI = function(data){
//here the logic fo calling the endpoint
};
//this is the function that handles data receiving
// it passes data from the buffer to the api, then clean the buffer
//this is the "debounced" search
// it runs after 500ms from its first call, just once in 500ms
var search = _.debounce(function(){
var keyword = document.getElementById('searchbox').value;
doSearch(keyword); //this performs server call and displays results
}, 500);
//this is the keyboard event
document.getElementById('searchbox').addEventListener('keypress', search);
//a generic function to call api endpoints
function apiCall(host, method, endpoint, params, callback){
var url = host + endpoint;
http(method, url, params, callback);
}
//this is some API for a foo.com web service
var fooAPI = _(apiCall).partial('http://foo.com');
var foo_listPosts = _(fooAPI).partial('GET', '/posts');
var foo_savePost = _(fooAPI).partial('POST', '/post');
//array of async resources to be loaded
var paths = ['file1.xml', 'file2.xml', 'file3.xml'];
//finalizing function, to be called after all async operations are completed
var finalize = _.after(function(){
alert('this is the last execution!');
}, paths.length);
//the callback for the ajax call
var callback = function(fileIndex){