~ubuntu-branches/ubuntu/utopic/codemirror-js/utopic

« back to all changes in this revision

Viewing changes to mode/coffeescript/index.html

  • Committer: Package Import Robot
  • Author(s): David Paleino
  • Date: 2012-04-12 12:25:28 UTC
  • Revision ID: package-import@ubuntu.com-20120412122528-8xp5a8frj4h1d3ee
Tags: upstream-2.23
Import upstream version 2.23

Show diffs side-by-side

added added

removed removed

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