SlideShare uma empresa Scribd logo
1 de 13
Baixar para ler offline
Underscore.js
 an introduction
Collections in JS are a pain!
What do I get?
_.functions(_) => [ 'after', 'all', 'any', 'bind', 'bindAll', 'clone',
'compact', 'compose', 'contains', 'debounce', 'defaults',
'defer', 'delay', 'difference', 'each', 'escape'', 'extend', 'filter',
'find', 'first', 'flatten', 'functions', 'groupBy', 'head', 'identity',
'include', 'indexOf', 'initial', 'intersect', 'intersection', 'invoke',
'isArguments', 'isArray', 'isBoolean', 'isDate', 'isElement',
'isEmpty', 'isEqual', 'isFunction', 'isNaN', 'isNull', 'isNumber',
'isObject', 'isRegExp', 'isString', 'isUndefined', 'keys', 'last',
'lastIndexOf', 'map', 'max', 'memoize', 'methods', 'min',
'mixin', 'noConflict', 'once', 'pluck', 'range', 'reduce',
'reduceRight', 'reject', 'rest', 'select', 'shuffle', 'size', 'some',
'sortBy', 'sortedIndex', 'tail', 'tap', 'template', 'throttle', 'times',
'toArray', 'union', 'uniq', 'unique', 'uniqueId', 'values',
'without', 'wrap', 'zip' ]
Functional vs Object-Oriented
Object-Oriented style:
_(arr).pluck('name')

Functional style:
_.pluck(arr, 'name')
Sorting an array of objects
var ppl = [ { name: 'Alice', age: 20 }, { name:
'Bob', age: 18 }, { name: 'Charles', age: 23 } ]

_.sortBy(ppl, function(x){ return -1 * x.age })
=> [{"name":"Charles","age":23},
   {"name":"Alice","age":20},
   {"name":"Bob","age":18}]
Chaining multiple functions
var ppl = [ { name: 'Alice', age: 20 }, { name:
'Bob', age: 18 }, { name: 'Charles', age: 23 }, {
name: 'Roberto', age:21 }]

_(ppl).chain()
.reject(function(x) { return /ob/i.test(x.name) })
.sortBy(function(x) { return -1 * x.age })
.pluck('name').value()
   => ["Charles", "Alice" ]
Using "range" and "reduce" to make
a factorial function
_.range(1,11) = [1,2,3,4,5,6,7,8,9,10]

var fac = function(x) {
   return _.reduce(_.range(1,x+1),
       function(total, y) { return total * y })
}
Array/object equality
['hello'] == ['hello']
=> false
{foo:'bar'} == {foo:'bar'}
=> false

_.isEqual(['hello'], ['hello'])
=> true
_.isEqual({foo:'bar'}, {foo:'bar'})
"Inheritance", _-style
var foo = { one: 1, two: 2 }
var bar = { three: 3 }

_.extend(foo,bar)
=> {"one":1,"two":2,"three":3}
Throttling
var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);
Places you can use it
Thanks!
Sebastian Motraghi

@seb_m               http://blog.motraghi.us

@xoxco                     http://xoxco.com

Mais conteúdo relacionado

Mais procurados

Handbook - From jQuery to YUI 3
Handbook - From jQuery to YUI 3Handbook - From jQuery to YUI 3
Handbook - From jQuery to YUI 3
Ying-Hsiang Liao
 
Feeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds APIFeeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds API
Alex S
 
Domótica. Test de conocimientos
Domótica. Test de conocimientosDomótica. Test de conocimientos
Domótica. Test de conocimientos
Jesús Amieiro
 

Mais procurados (20)

PHP Profiling
PHP ProfilingPHP Profiling
PHP Profiling
 
JS programowanie obiektowe
JS  programowanie obiektoweJS  programowanie obiektowe
JS programowanie obiektowe
 
Vue.jsのユニットテスト
Vue.jsのユニットテストVue.jsのユニットテスト
Vue.jsのユニットテスト
 
modern javascript, unobtrusive javascript, jquery
modern javascript, unobtrusive javascript, jquerymodern javascript, unobtrusive javascript, jquery
modern javascript, unobtrusive javascript, jquery
 
Handbook - From jQuery to YUI 3
Handbook - From jQuery to YUI 3Handbook - From jQuery to YUI 3
Handbook - From jQuery to YUI 3
 
Gestire l'asincronia in javascript uno sguardo al futuro!
Gestire l'asincronia in javascript  uno sguardo al futuro!Gestire l'asincronia in javascript  uno sguardo al futuro!
Gestire l'asincronia in javascript uno sguardo al futuro!
 
Introducing Ballerina
Introducing BallerinaIntroducing Ballerina
Introducing Ballerina
 
Jquery2
Jquery2Jquery2
Jquery2
 
アプリ設定の保存をシンプルに
アプリ設定の保存をシンプルにアプリ設定の保存をシンプルに
アプリ設定の保存をシンプルに
 
Фатальный недостаток Node.js
Фатальный недостаток Node.jsФатальный недостаток Node.js
Фатальный недостаток Node.js
 
Base datos
Base datosBase datos
Base datos
 
Java script.trend(spec)
Java script.trend(spec)Java script.trend(spec)
Java script.trend(spec)
 
Index2
Index2Index2
Index2
 
Feeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds APIFeeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds API
 
Domótica. Test de conocimientos
Domótica. Test de conocimientosDomótica. Test de conocimientos
Domótica. Test de conocimientos
 
Palestra sobre MongoDB com PHP no PHP'n'Rio
Palestra sobre MongoDB com PHP no PHP'n'Rio Palestra sobre MongoDB com PHP no PHP'n'Rio
Palestra sobre MongoDB com PHP no PHP'n'Rio
 
モナド: お前はもう知っている
モナド: お前はもう知っているモナド: お前はもう知っている
モナド: お前はもう知っている
 
PyconRu 2016. Осторожно, DSL!
PyconRu 2016. Осторожно, DSL!PyconRu 2016. Осторожно, DSL!
PyconRu 2016. Осторожно, DSL!
 
Jquery ui, ajax
Jquery ui, ajaxJquery ui, ajax
Jquery ui, ajax
 
Sis quiz
Sis quizSis quiz
Sis quiz
 

Underscore.js

  • 2. Collections in JS are a pain!
  • 3.
  • 4. What do I get? _.functions(_) => [ 'after', 'all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', 'contains', 'debounce', 'defaults', 'defer', 'delay', 'difference', 'each', 'escape'', 'extend', 'filter', 'find', 'first', 'flatten', 'functions', 'groupBy', 'head', 'identity', 'include', 'indexOf', 'initial', 'intersect', 'intersection', 'invoke', 'isArguments', 'isArray', 'isBoolean', 'isDate', 'isElement', 'isEmpty', 'isEqual', 'isFunction', 'isNaN', 'isNull', 'isNumber', 'isObject', 'isRegExp', 'isString', 'isUndefined', 'keys', 'last', 'lastIndexOf', 'map', 'max', 'memoize', 'methods', 'min', 'mixin', 'noConflict', 'once', 'pluck', 'range', 'reduce', 'reduceRight', 'reject', 'rest', 'select', 'shuffle', 'size', 'some', 'sortBy', 'sortedIndex', 'tail', 'tap', 'template', 'throttle', 'times', 'toArray', 'union', 'uniq', 'unique', 'uniqueId', 'values', 'without', 'wrap', 'zip' ]
  • 5. Functional vs Object-Oriented Object-Oriented style: _(arr).pluck('name') Functional style: _.pluck(arr, 'name')
  • 6. Sorting an array of objects var ppl = [ { name: 'Alice', age: 20 }, { name: 'Bob', age: 18 }, { name: 'Charles', age: 23 } ] _.sortBy(ppl, function(x){ return -1 * x.age }) => [{"name":"Charles","age":23}, {"name":"Alice","age":20}, {"name":"Bob","age":18}]
  • 7. Chaining multiple functions var ppl = [ { name: 'Alice', age: 20 }, { name: 'Bob', age: 18 }, { name: 'Charles', age: 23 }, { name: 'Roberto', age:21 }] _(ppl).chain() .reject(function(x) { return /ob/i.test(x.name) }) .sortBy(function(x) { return -1 * x.age }) .pluck('name').value() => ["Charles", "Alice" ]
  • 8. Using "range" and "reduce" to make a factorial function _.range(1,11) = [1,2,3,4,5,6,7,8,9,10] var fac = function(x) { return _.reduce(_.range(1,x+1), function(total, y) { return total * y }) }
  • 9. Array/object equality ['hello'] == ['hello'] => false {foo:'bar'} == {foo:'bar'} => false _.isEqual(['hello'], ['hello']) => true _.isEqual({foo:'bar'}, {foo:'bar'})
  • 10. "Inheritance", _-style var foo = { one: 1, two: 2 } var bar = { three: 3 } _.extend(foo,bar) => {"one":1,"two":2,"three":3}
  • 11. Throttling var throttled = _.throttle(updatePosition, 100); $(window).scroll(throttled);
  • 12. Places you can use it
  • 13. Thanks! Sebastian Motraghi @seb_m http://blog.motraghi.us @xoxco http://xoxco.com