/examples/underscore.coffee

http://github.com/jashkenas/coffee-script · CoffeeScript · 682 lines · 341 code · 178 blank · 163 comment · 100 complexity · 86860074d61731198d9bcde74b97fbce MD5 · raw file

  1. # **Underscore.coffee
  2. # (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**
  3. # Underscore is freely distributable under the terms of the
  4. # [MIT license](http://en.wikipedia.org/wiki/MIT_License).
  5. # Portions of Underscore are inspired by or borrowed from
  6. # [Prototype.js](http://prototypejs.org/api), Oliver Steele's
  7. # [Functional](http://osteele.com), and John Resig's
  8. # [Micro-Templating](http://ejohn.org).
  9. # For all details and documentation:
  10. # http://documentcloud.github.com/underscore/
  11. # Baseline setup
  12. # --------------
  13. # Establish the root object, `window` in the browser, or `global` on the server.
  14. root = this
  15. # Save the previous value of the `_` variable.
  16. previousUnderscore = root._
  17. # Establish the object that gets thrown to break out of a loop iteration.
  18. # `StopIteration` is SOP on Mozilla.
  19. breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
  20. # Helper function to escape **RegExp** contents, because JS doesn't have one.
  21. escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1')
  22. # Save bytes in the minified (but not gzipped) version:
  23. ArrayProto = Array.prototype
  24. ObjProto = Object.prototype
  25. # Create quick reference variables for speed access to core prototypes.
  26. slice = ArrayProto.slice
  27. unshift = ArrayProto.unshift
  28. toString = ObjProto.toString
  29. hasOwnProperty = ObjProto.hasOwnProperty
  30. propertyIsEnumerable = ObjProto.propertyIsEnumerable
  31. # All **ECMA5** native implementations we hope to use are declared here.
  32. nativeForEach = ArrayProto.forEach
  33. nativeMap = ArrayProto.map
  34. nativeReduce = ArrayProto.reduce
  35. nativeReduceRight = ArrayProto.reduceRight
  36. nativeFilter = ArrayProto.filter
  37. nativeEvery = ArrayProto.every
  38. nativeSome = ArrayProto.some
  39. nativeIndexOf = ArrayProto.indexOf
  40. nativeLastIndexOf = ArrayProto.lastIndexOf
  41. nativeIsArray = Array.isArray
  42. nativeKeys = Object.keys
  43. # Create a safe reference to the Underscore object for use below.
  44. _ = (obj) -> new wrapper(obj)
  45. # Export the Underscore object for **CommonJS**.
  46. if typeof(exports) != 'undefined' then exports._ = _
  47. # Export Underscore to global scope.
  48. root._ = _
  49. # Current version.
  50. _.VERSION = '1.1.0'
  51. # Collection Functions
  52. # --------------------
  53. # The cornerstone, an **each** implementation.
  54. # Handles objects implementing **forEach**, arrays, and raw objects.
  55. _.each = (obj, iterator, context) ->
  56. try
  57. if nativeForEach and obj.forEach is nativeForEach
  58. obj.forEach iterator, context
  59. else if _.isNumber obj.length
  60. iterator.call context, obj[i], i, obj for i in [0...obj.length]
  61. else
  62. iterator.call context, val, key, obj for own key, val of obj
  63. catch e
  64. throw e if e isnt breaker
  65. obj
  66. # Return the results of applying the iterator to each element. Use JavaScript
  67. # 1.6's version of **map**, if possible.
  68. _.map = (obj, iterator, context) ->
  69. return obj.map(iterator, context) if nativeMap and obj.map is nativeMap
  70. results = []
  71. _.each obj, (value, index, list) ->
  72. results.push iterator.call context, value, index, list
  73. results
  74. # **Reduce** builds up a single result from a list of values. Also known as
  75. # **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.
  76. _.reduce = (obj, iterator, memo, context) ->
  77. if nativeReduce and obj.reduce is nativeReduce
  78. iterator = _.bind iterator, context if context
  79. return obj.reduce iterator, memo
  80. _.each obj, (value, index, list) ->
  81. memo = iterator.call context, memo, value, index, list
  82. memo
  83. # The right-associative version of **reduce**, also known as **foldr**. Uses
  84. # JavaScript 1.8's version of **reduceRight**, if available.
  85. _.reduceRight = (obj, iterator, memo, context) ->
  86. if nativeReduceRight and obj.reduceRight is nativeReduceRight
  87. iterator = _.bind iterator, context if context
  88. return obj.reduceRight iterator, memo
  89. reversed = _.clone(_.toArray(obj)).reverse()
  90. _.reduce reversed, iterator, memo, context
  91. # Return the first value which passes a truth test.
  92. _.detect = (obj, iterator, context) ->
  93. result = null
  94. _.each obj, (value, index, list) ->
  95. if iterator.call context, value, index, list
  96. result = value
  97. _.breakLoop()
  98. result
  99. # Return all the elements that pass a truth test. Use JavaScript 1.6's
  100. # **filter**, if it exists.
  101. _.filter = (obj, iterator, context) ->
  102. return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter
  103. results = []
  104. _.each obj, (value, index, list) ->
  105. results.push value if iterator.call context, value, index, list
  106. results
  107. # Return all the elements for which a truth test fails.
  108. _.reject = (obj, iterator, context) ->
  109. results = []
  110. _.each obj, (value, index, list) ->
  111. results.push value if not iterator.call context, value, index, list
  112. results
  113. # Determine whether all of the elements match a truth test. Delegate to
  114. # JavaScript 1.6's **every**, if it is present.
  115. _.every = (obj, iterator, context) ->
  116. iterator ||= _.identity
  117. return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
  118. result = true
  119. _.each obj, (value, index, list) ->
  120. _.breakLoop() unless (result = result and iterator.call(context, value, index, list))
  121. result
  122. # Determine if at least one element in the object matches a truth test. Use
  123. # JavaScript 1.6's **some**, if it exists.
  124. _.some = (obj, iterator, context) ->
  125. iterator ||= _.identity
  126. return obj.some iterator, context if nativeSome and obj.some is nativeSome
  127. result = false
  128. _.each obj, (value, index, list) ->
  129. _.breakLoop() if (result = iterator.call(context, value, index, list))
  130. result
  131. # Determine if a given value is included in the array or object,
  132. # based on `===`.
  133. _.include = (obj, target) ->
  134. return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf
  135. return true for own key, val of obj when val is target
  136. false
  137. # Invoke a method with arguments on every item in a collection.
  138. _.invoke = (obj, method) ->
  139. args = _.rest arguments, 2
  140. (if method then val[method] else val).apply(val, args) for val in obj
  141. # Convenience version of a common use case of **map**: fetching a property.
  142. _.pluck = (obj, key) ->
  143. _.map(obj, (val) -> val[key])
  144. # Return the maximum item or (item-based computation).
  145. _.max = (obj, iterator, context) ->
  146. return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
  147. result = computed: -Infinity
  148. _.each obj, (value, index, list) ->
  149. computed = if iterator then iterator.call(context, value, index, list) else value
  150. computed >= result.computed and (result = {value: value, computed: computed})
  151. result.value
  152. # Return the minimum element (or element-based computation).
  153. _.min = (obj, iterator, context) ->
  154. return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
  155. result = computed: Infinity
  156. _.each obj, (value, index, list) ->
  157. computed = if iterator then iterator.call(context, value, index, list) else value
  158. computed < result.computed and (result = {value: value, computed: computed})
  159. result.value
  160. # Sort the object's values by a criterion produced by an iterator.
  161. _.sortBy = (obj, iterator, context) ->
  162. _.pluck(((_.map obj, (value, index, list) ->
  163. {value: value, criteria: iterator.call(context, value, index, list)}
  164. ).sort((left, right) ->
  165. a = left.criteria; b = right.criteria
  166. if a < b then -1 else if a > b then 1 else 0
  167. )), 'value')
  168. # Use a comparator function to figure out at what index an object should
  169. # be inserted so as to maintain order. Uses binary search.
  170. _.sortedIndex = (array, obj, iterator) ->
  171. iterator ||= _.identity
  172. low = 0
  173. high = array.length
  174. while low < high
  175. mid = (low + high) >> 1
  176. if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
  177. low
  178. # Convert anything iterable into a real, live array.
  179. _.toArray = (iterable) ->
  180. return [] if (!iterable)
  181. return iterable.toArray() if (iterable.toArray)
  182. return iterable if (_.isArray(iterable))
  183. return slice.call(iterable) if (_.isArguments(iterable))
  184. _.values(iterable)
  185. # Return the number of elements in an object.
  186. _.size = (obj) -> _.toArray(obj).length
  187. # Array Functions
  188. # ---------------
  189. # Get the first element of an array. Passing `n` will return the first N
  190. # values in the array. Aliased as **head**. The `guard` check allows it to work
  191. # with **map**.
  192. _.first = (array, n, guard) ->
  193. if n and not guard then slice.call(array, 0, n) else array[0]
  194. # Returns everything but the first entry of the array. Aliased as **tail**.
  195. # Especially useful on the arguments object. Passing an `index` will return
  196. # the rest of the values in the array from that index onward. The `guard`
  197. # check allows it to work with **map**.
  198. _.rest = (array, index, guard) ->
  199. slice.call(array, if _.isUndefined(index) or guard then 1 else index)
  200. # Get the last element of an array.
  201. _.last = (array) -> array[array.length - 1]
  202. # Trim out all falsy values from an array.
  203. _.compact = (array) -> item for item in array when item
  204. # Return a completely flattened version of an array.
  205. _.flatten = (array) ->
  206. _.reduce array, (memo, value) ->
  207. return memo.concat(_.flatten(value)) if _.isArray value
  208. memo.push value
  209. memo
  210. , []
  211. # Return a version of the array that does not contain the specified value(s).
  212. _.without = (array) ->
  213. values = _.rest arguments
  214. val for val in _.toArray(array) when not _.include values, val
  215. # Produce a duplicate-free version of the array. If the array has already
  216. # been sorted, you have the option of using a faster algorithm.
  217. _.uniq = (array, isSorted) ->
  218. memo = []
  219. for el, i in _.toArray array
  220. memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
  221. memo
  222. # Produce an array that contains every item shared between all the
  223. # passed-in arrays.
  224. _.intersect = (array) ->
  225. rest = _.rest arguments
  226. _.select _.uniq(array), (item) ->
  227. _.all rest, (other) ->
  228. _.indexOf(other, item) >= 0
  229. # Zip together multiple lists into a single array -- elements that share
  230. # an index go together.
  231. _.zip = ->
  232. length = _.max _.pluck arguments, 'length'
  233. results = new Array length
  234. for i in [0...length]
  235. results[i] = _.pluck arguments, String i
  236. results
  237. # If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),
  238. # we need this function. Return the position of the first occurrence of an
  239. # item in an array, or -1 if the item is not included in the array.
  240. _.indexOf = (array, item) ->
  241. return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
  242. i = 0; l = array.length
  243. while l - i
  244. if array[i] is item then return i else i++
  245. -1
  246. # Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,
  247. # if possible.
  248. _.lastIndexOf = (array, item) ->
  249. return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf
  250. i = array.length
  251. while i
  252. if array[i] is item then return i else i--
  253. -1
  254. # Generate an integer Array containing an arithmetic progression. A port of
  255. # [the native Python **range** function](http://docs.python.org/library/functions.html#range).
  256. _.range = (start, stop, step) ->
  257. a = arguments
  258. solo = a.length <= 1
  259. i = start = if solo then 0 else a[0]
  260. stop = if solo then a[0] else a[1]
  261. step = a[2] or 1
  262. len = Math.ceil((stop - start) / step)
  263. return [] if len <= 0
  264. range = new Array len
  265. idx = 0
  266. loop
  267. return range if (if step > 0 then i - stop else stop - i) >= 0
  268. range[idx] = i
  269. idx++
  270. i+= step
  271. # Function Functions
  272. # ------------------
  273. # Create a function bound to a given object (assigning `this`, and arguments,
  274. # optionally). Binding with arguments is also known as **curry**.
  275. _.bind = (func, obj) ->
  276. args = _.rest arguments, 2
  277. -> func.apply obj or root, args.concat arguments
  278. # Bind all of an object's methods to that object. Useful for ensuring that
  279. # all callbacks defined on an object belong to it.
  280. _.bindAll = (obj) ->
  281. funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
  282. _.each funcs, (f) -> obj[f] = _.bind obj[f], obj
  283. obj
  284. # Delays a function for the given number of milliseconds, and then calls
  285. # it with the arguments supplied.
  286. _.delay = (func, wait) ->
  287. args = _.rest arguments, 2
  288. setTimeout((-> func.apply(func, args)), wait)
  289. # Memoize an expensive function by storing its results.
  290. _.memoize = (func, hasher) ->
  291. memo = {}
  292. hasher or= _.identity
  293. ->
  294. key = hasher.apply this, arguments
  295. return memo[key] if key of memo
  296. memo[key] = func.apply this, arguments
  297. # Defers a function, scheduling it to run after the current call stack has
  298. # cleared.
  299. _.defer = (func) ->
  300. _.delay.apply _, [func, 1].concat _.rest arguments
  301. # Returns the first function passed as an argument to the second,
  302. # allowing you to adjust arguments, run code before and after, and
  303. # conditionally execute the original function.
  304. _.wrap = (func, wrapper) ->
  305. -> wrapper.apply wrapper, [func].concat arguments
  306. # Returns a function that is the composition of a list of functions, each
  307. # consuming the return value of the function that follows.
  308. _.compose = ->
  309. funcs = arguments
  310. ->
  311. args = arguments
  312. for i in [funcs.length - 1..0] by -1
  313. args = [funcs[i].apply(this, args)]
  314. args[0]
  315. # Object Functions
  316. # ----------------
  317. # Retrieve the names of an object's properties.
  318. _.keys = nativeKeys or (obj) ->
  319. return _.range 0, obj.length if _.isArray(obj)
  320. key for key, val of obj
  321. # Retrieve the values of an object's properties.
  322. _.values = (obj) ->
  323. _.map obj, _.identity
  324. # Return a sorted list of the function names available in Underscore.
  325. _.functions = (obj) ->
  326. _.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
  327. # Extend a given object with all of the properties in a source object.
  328. _.extend = (obj) ->
  329. for source in _.rest(arguments)
  330. obj[key] = val for key, val of source
  331. obj
  332. # Create a (shallow-cloned) duplicate of an object.
  333. _.clone = (obj) ->
  334. return obj.slice 0 if _.isArray obj
  335. _.extend {}, obj
  336. # Invokes interceptor with the obj, and then returns obj.
  337. # The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.
  338. _.tap = (obj, interceptor) ->
  339. interceptor obj
  340. obj
  341. # Perform a deep comparison to check if two objects are equal.
  342. _.isEqual = (a, b) ->
  343. # Check object identity.
  344. return true if a is b
  345. # Different types?
  346. atype = typeof(a); btype = typeof(b)
  347. return false if atype isnt btype
  348. # Basic equality test (watch out for coercions).
  349. return true if `a == b`
  350. # One is falsy and the other truthy.
  351. return false if (!a and b) or (a and !b)
  352. # One of them implements an `isEqual()`?
  353. return a.isEqual(b) if a.isEqual
  354. # Check dates' integer values.
  355. return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)
  356. # Both are NaN?
  357. return false if _.isNaN(a) and _.isNaN(b)
  358. # Compare regular expressions.
  359. if _.isRegExp(a) and _.isRegExp(b)
  360. return a.source is b.source and
  361. a.global is b.global and
  362. a.ignoreCase is b.ignoreCase and
  363. a.multiline is b.multiline
  364. # If a is not an object by this point, we can't handle it.
  365. return false if atype isnt 'object'
  366. # Check for different array lengths before comparing contents.
  367. return false if a.length and (a.length isnt b.length)
  368. # Nothing else worked, deep compare the contents.
  369. aKeys = _.keys(a); bKeys = _.keys(b)
  370. # Different object sizes?
  371. return false if aKeys.length isnt bKeys.length
  372. # Recursive comparison of contents.
  373. return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])
  374. true
  375. # Is a given array or object empty?
  376. _.isEmpty = (obj) ->
  377. return obj.length is 0 if _.isArray(obj) or _.isString(obj)
  378. return false for own key of obj
  379. true
  380. # Is a given value a DOM element?
  381. _.isElement = (obj) -> obj and obj.nodeType is 1
  382. # Is a given value an array?
  383. _.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)
  384. # Is a given variable an arguments object?
  385. _.isArguments = (obj) -> obj and obj.callee
  386. # Is the given value a function?
  387. _.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
  388. # Is the given value a string?
  389. _.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
  390. # Is a given value a number?
  391. _.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
  392. # Is a given value a boolean?
  393. _.isBoolean = (obj) -> obj is true or obj is false
  394. # Is a given value a Date?
  395. _.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
  396. # Is the given value a regular expression?
  397. _.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
  398. # Is the given value NaN -- this one is interesting. `NaN != NaN`, and
  399. # `isNaN(undefined) == true`, so we make sure it's a number first.
  400. _.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)
  401. # Is a given value equal to null?
  402. _.isNull = (obj) -> obj is null
  403. # Is a given variable undefined?
  404. _.isUndefined = (obj) -> typeof obj is 'undefined'
  405. # Utility Functions
  406. # -----------------
  407. # Run Underscore.js in noConflict mode, returning the `_` variable to its
  408. # previous owner. Returns a reference to the Underscore object.
  409. _.noConflict = ->
  410. root._ = previousUnderscore
  411. this
  412. # Keep the identity function around for default iterators.
  413. _.identity = (value) -> value
  414. # Run a function `n` times.
  415. _.times = (n, iterator, context) ->
  416. iterator.call context, i for i in [0...n]
  417. # Break out of the middle of an iteration.
  418. _.breakLoop = -> throw breaker
  419. # Add your own custom functions to the Underscore object, ensuring that
  420. # they're correctly added to the OOP wrapper as well.
  421. _.mixin = (obj) ->
  422. for name in _.functions(obj)
  423. addToWrapper name, _[name] = obj[name]
  424. # Generate a unique integer id (unique within the entire client session).
  425. # Useful for temporary DOM ids.
  426. idCounter = 0
  427. _.uniqueId = (prefix) ->
  428. (prefix or '') + idCounter++
  429. # By default, Underscore uses **ERB**-style template delimiters, change the
  430. # following template settings to use alternative delimiters.
  431. _.templateSettings = {
  432. start: '<%'
  433. end: '%>'
  434. interpolate: /<%=(.+?)%>/g
  435. }
  436. # JavaScript templating a-la **ERB**, pilfered from John Resig's
  437. # *Secrets of the JavaScript Ninja*, page 83.
  438. # Single-quote fix from Rick Strahl.
  439. # With alterations for arbitrary delimiters, and to preserve whitespace.
  440. _.template = (str, data) ->
  441. c = _.templateSettings
  442. endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g")
  443. fn = new Function 'obj',
  444. 'var p=[],print=function(){p.push.apply(p,arguments);};' +
  445. 'with(obj||{}){p.push(\'' +
  446. str.replace(/\r/g, '\\r')
  447. .replace(/\n/g, '\\n')
  448. .replace(/\t/g, '\\t')
  449. .replace(endMatch,"✄")
  450. .split("'").join("\\'")
  451. .split("✄").join("'")
  452. .replace(c.interpolate, "',$1,'")
  453. .split(c.start).join("');")
  454. .split(c.end).join("p.push('") +
  455. "');}return p.join('');"
  456. if data then fn(data) else fn
  457. # Aliases
  458. # -------
  459. _.forEach = _.each
  460. _.foldl = _.inject = _.reduce
  461. _.foldr = _.reduceRight
  462. _.select = _.filter
  463. _.all = _.every
  464. _.any = _.some
  465. _.contains = _.include
  466. _.head = _.first
  467. _.tail = _.rest
  468. _.methods = _.functions
  469. # Setup the OOP Wrapper
  470. # ---------------------
  471. # If Underscore is called as a function, it returns a wrapped object that
  472. # can be used OO-style. This wrapper holds altered versions of all the
  473. # underscore functions. Wrapped objects may be chained.
  474. wrapper = (obj) ->
  475. this._wrapped = obj
  476. this
  477. # Helper function to continue chaining intermediate results.
  478. result = (obj, chain) ->
  479. if chain then _(obj).chain() else obj
  480. # A method to easily add functions to the OOP wrapper.
  481. addToWrapper = (name, func) ->
  482. wrapper.prototype[name] = ->
  483. args = _.toArray arguments
  484. unshift.call args, this._wrapped
  485. result func.apply(_, args), this._chain
  486. # Add all ofthe Underscore functions to the wrapper object.
  487. _.mixin _
  488. # Add all mutator Array functions to the wrapper.
  489. _.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
  490. method = Array.prototype[name]
  491. wrapper.prototype[name] = ->
  492. method.apply(this._wrapped, arguments)
  493. result(this._wrapped, this._chain)
  494. # Add all accessor Array functions to the wrapper.
  495. _.each ['concat', 'join', 'slice'], (name) ->
  496. method = Array.prototype[name]
  497. wrapper.prototype[name] = ->
  498. result(method.apply(this._wrapped, arguments), this._chain)
  499. # Start chaining a wrapped Underscore object.
  500. wrapper::chain = ->
  501. this._chain = true
  502. this
  503. # Extracts the result from a wrapped and chained object.
  504. wrapper::value = -> this._wrapped