Underscore.js

2,342 views

Published on

Published in: Technology, Spiritual
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,342
On SlideShare
0
From Embeds
0
Number of Embeds
16
Actions
Shares
0
Downloads
34
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Underscore.js

  1. 1. Underscore.js an introduction
  2. 2. Collections in JS are a pain!
  3. 3. 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 ]
  4. 4. Functional vs Object-OrientedObject-Oriented style:_(arr).pluck(name)Functional style:_.pluck(arr, name)
  5. 5. Sorting an array of objectsvar 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}]
  6. 6. Chaining multiple functionsvar 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" ]
  7. 7. Using "range" and "reduce" to makea 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 })}
  8. 8. Array/object equality[hello] == [hello]=> false{foo:bar} == {foo:bar}=> false_.isEqual([hello], [hello])=> true_.isEqual({foo:bar}, {foo:bar})
  9. 9. "Inheritance", _-stylevar foo = { one: 1, two: 2 }var bar = { three: 3 }_.extend(foo,bar)=> {"one":1,"two":2,"three":3}
  10. 10. Throttlingvar throttled = _.throttle(updatePosition, 100);$(window).scroll(throttled);
  11. 11. Places you can use it
  12. 12. Thanks!Sebastian Motraghi@seb_m http://blog.motraghi.us@xoxco http://xoxco.com

×