PageRenderTime 28ms CodeModel.GetById 2ms app.highlight 20ms RepoModel.GetById 1ms app.codeStats 0ms

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