mouth 0.8.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (41) hide show
  1. data/.gitignore +7 -0
  2. data/Capfile +26 -0
  3. data/Gemfile +3 -0
  4. data/MIT-LICENSE +20 -0
  5. data/README.md +138 -0
  6. data/Rakefile +19 -0
  7. data/TODO +32 -0
  8. data/bin/mouth +77 -0
  9. data/bin/mouth-console +18 -0
  10. data/bin/mouth-endoscope +18 -0
  11. data/lib/mouth.rb +61 -0
  12. data/lib/mouth/dashboard.rb +25 -0
  13. data/lib/mouth/endoscope.rb +120 -0
  14. data/lib/mouth/endoscope/public/222222_256x240_icons_icons.png +0 -0
  15. data/lib/mouth/endoscope/public/application.css +464 -0
  16. data/lib/mouth/endoscope/public/application.js +938 -0
  17. data/lib/mouth/endoscope/public/backbone.js +1158 -0
  18. data/lib/mouth/endoscope/public/d3.js +4707 -0
  19. data/lib/mouth/endoscope/public/d3.time.js +687 -0
  20. data/lib/mouth/endoscope/public/jquery-ui-1.8.16.custom.min.js +177 -0
  21. data/lib/mouth/endoscope/public/jquery.js +4 -0
  22. data/lib/mouth/endoscope/public/json2.js +480 -0
  23. data/lib/mouth/endoscope/public/keymaster.js +163 -0
  24. data/lib/mouth/endoscope/public/linen.js +46 -0
  25. data/lib/mouth/endoscope/public/seven.css +68 -0
  26. data/lib/mouth/endoscope/public/seven.js +291 -0
  27. data/lib/mouth/endoscope/public/underscore.js +931 -0
  28. data/lib/mouth/endoscope/views/dashboard.erb +67 -0
  29. data/lib/mouth/graph.rb +58 -0
  30. data/lib/mouth/instrument.rb +56 -0
  31. data/lib/mouth/record.rb +72 -0
  32. data/lib/mouth/runner.rb +89 -0
  33. data/lib/mouth/sequence.rb +284 -0
  34. data/lib/mouth/source.rb +76 -0
  35. data/lib/mouth/sucker.rb +235 -0
  36. data/lib/mouth/version.rb +3 -0
  37. data/mouth.gemspec +28 -0
  38. data/test/sequence_test.rb +163 -0
  39. data/test/sucker_test.rb +55 -0
  40. data/test/test_helper.rb +5 -0
  41. metadata +167 -0
@@ -0,0 +1,931 @@
1
+ // Underscore.js 1.2.0
2
+ // (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
3
+ // Underscore is freely distributable under the MIT license.
4
+ // Portions of Underscore are inspired or borrowed from Prototype,
5
+ // Oliver Steele's Functional, and John Resig's Micro-Templating.
6
+ // For all details and documentation:
7
+ // http://documentcloud.github.com/underscore
8
+
9
+ (function() {
10
+
11
+ // Baseline setup
12
+ // --------------
13
+
14
+ // Establish the root object, `window` in the browser, or `global` on the server.
15
+ var root = this;
16
+
17
+ // Save the previous value of the `_` variable.
18
+ var previousUnderscore = root._;
19
+
20
+ // Establish the object that gets returned to break out of a loop iteration.
21
+ var breaker = {};
22
+
23
+ // Save bytes in the minified (but not gzipped) version:
24
+ var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
25
+
26
+ // Create quick reference variables for speed access to core prototypes.
27
+ var slice = ArrayProto.slice,
28
+ unshift = ArrayProto.unshift,
29
+ toString = ObjProto.toString,
30
+ hasOwnProperty = ObjProto.hasOwnProperty;
31
+
32
+ // All **ECMAScript 5** native function implementations that we hope to use
33
+ // are declared here.
34
+ var
35
+ nativeForEach = ArrayProto.forEach,
36
+ nativeMap = ArrayProto.map,
37
+ nativeReduce = ArrayProto.reduce,
38
+ nativeReduceRight = ArrayProto.reduceRight,
39
+ nativeFilter = ArrayProto.filter,
40
+ nativeEvery = ArrayProto.every,
41
+ nativeSome = ArrayProto.some,
42
+ nativeIndexOf = ArrayProto.indexOf,
43
+ nativeLastIndexOf = ArrayProto.lastIndexOf,
44
+ nativeIsArray = Array.isArray,
45
+ nativeKeys = Object.keys,
46
+ nativeBind = FuncProto.bind;
47
+
48
+ // Create a safe reference to the Underscore object for use below.
49
+ var _ = function(obj) { return new wrapper(obj); };
50
+
51
+ // Export the Underscore object for **CommonJS**, with backwards-compatibility
52
+ // for the old `require()` API. If we're not in CommonJS, add `_` to the
53
+ // global object.
54
+ if (typeof module !== 'undefined' && module.exports) {
55
+ module.exports = _;
56
+ _._ = _;
57
+ } else {
58
+ // Exported as a string, for Closure Compiler "advanced" mode.
59
+ root['_'] = _;
60
+ }
61
+
62
+ // Current version.
63
+ _.VERSION = '1.2.0';
64
+
65
+ // Collection Functions
66
+ // --------------------
67
+
68
+ // The cornerstone, an `each` implementation, aka `forEach`.
69
+ // Handles objects with the built-in `forEach`, arrays, and raw objects.
70
+ // Delegates to **ECMAScript 5**'s native `forEach` if available.
71
+ var each = _.each = _.forEach = function(obj, iterator, context) {
72
+ if (obj == null) return;
73
+ if (nativeForEach && obj.forEach === nativeForEach) {
74
+ obj.forEach(iterator, context);
75
+ } else if (obj.length === +obj.length) {
76
+ for (var i = 0, l = obj.length; i < l; i++) {
77
+ if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
78
+ }
79
+ } else {
80
+ for (var key in obj) {
81
+ if (hasOwnProperty.call(obj, key)) {
82
+ if (iterator.call(context, obj[key], key, obj) === breaker) return;
83
+ }
84
+ }
85
+ }
86
+ };
87
+
88
+ // Return the results of applying the iterator to each element.
89
+ // Delegates to **ECMAScript 5**'s native `map` if available.
90
+ _.map = function(obj, iterator, context) {
91
+ var results = [];
92
+ if (obj == null) return results;
93
+ if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
94
+ each(obj, function(value, index, list) {
95
+ results[results.length] = iterator.call(context, value, index, list);
96
+ });
97
+ return results;
98
+ };
99
+
100
+ // **Reduce** builds up a single result from a list of values, aka `inject`,
101
+ // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
102
+ _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
103
+ var initial = memo !== void 0;
104
+ if (obj == null) obj = [];
105
+ if (nativeReduce && obj.reduce === nativeReduce) {
106
+ if (context) iterator = _.bind(iterator, context);
107
+ return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
108
+ }
109
+ each(obj, function(value, index, list) {
110
+ if (!initial) {
111
+ memo = value;
112
+ initial = true;
113
+ } else {
114
+ memo = iterator.call(context, memo, value, index, list);
115
+ }
116
+ });
117
+ if (!initial) throw new TypeError("Reduce of empty array with no initial value");
118
+ return memo;
119
+ };
120
+
121
+ // The right-associative version of reduce, also known as `foldr`.
122
+ // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
123
+ _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
124
+ if (obj == null) obj = [];
125
+ if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
126
+ if (context) iterator = _.bind(iterator, context);
127
+ return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
128
+ }
129
+ var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
130
+ return _.reduce(reversed, iterator, memo, context);
131
+ };
132
+
133
+ // Return the first value which passes a truth test. Aliased as `detect`.
134
+ _.find = _.detect = function(obj, iterator, context) {
135
+ var result;
136
+ any(obj, function(value, index, list) {
137
+ if (iterator.call(context, value, index, list)) {
138
+ result = value;
139
+ return true;
140
+ }
141
+ });
142
+ return result;
143
+ };
144
+
145
+ // Return all the elements that pass a truth test.
146
+ // Delegates to **ECMAScript 5**'s native `filter` if available.
147
+ // Aliased as `select`.
148
+ _.filter = _.select = function(obj, iterator, context) {
149
+ var results = [];
150
+ if (obj == null) return results;
151
+ if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
152
+ each(obj, function(value, index, list) {
153
+ if (iterator.call(context, value, index, list)) results[results.length] = value;
154
+ });
155
+ return results;
156
+ };
157
+
158
+ // Return all the elements for which a truth test fails.
159
+ _.reject = function(obj, iterator, context) {
160
+ var results = [];
161
+ if (obj == null) return results;
162
+ each(obj, function(value, index, list) {
163
+ if (!iterator.call(context, value, index, list)) results[results.length] = value;
164
+ });
165
+ return results;
166
+ };
167
+
168
+ // Determine whether all of the elements match a truth test.
169
+ // Delegates to **ECMAScript 5**'s native `every` if available.
170
+ // Aliased as `all`.
171
+ _.every = _.all = function(obj, iterator, context) {
172
+ var result = true;
173
+ if (obj == null) return result;
174
+ if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
175
+ each(obj, function(value, index, list) {
176
+ if (!(result = result && iterator.call(context, value, index, list))) return breaker;
177
+ });
178
+ return result;
179
+ };
180
+
181
+ // Determine if at least one element in the object matches a truth test.
182
+ // Delegates to **ECMAScript 5**'s native `some` if available.
183
+ // Aliased as `any`.
184
+ var any = _.some = _.any = function(obj, iterator, context) {
185
+ iterator = iterator || _.identity;
186
+ var result = false;
187
+ if (obj == null) return result;
188
+ if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
189
+ each(obj, function(value, index, list) {
190
+ if (result |= iterator.call(context, value, index, list)) return breaker;
191
+ });
192
+ return !!result;
193
+ };
194
+
195
+ // Determine if a given value is included in the array or object using `===`.
196
+ // Aliased as `contains`.
197
+ _.include = _.contains = function(obj, target) {
198
+ var found = false;
199
+ if (obj == null) return found;
200
+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
201
+ any(obj, function(value) {
202
+ if (found = value === target) return true;
203
+ });
204
+ return found;
205
+ };
206
+
207
+ // Invoke a method (with arguments) on every item in a collection.
208
+ _.invoke = function(obj, method) {
209
+ var args = slice.call(arguments, 2);
210
+ return _.map(obj, function(value) {
211
+ return (method.call ? method || value : value[method]).apply(value, args);
212
+ });
213
+ };
214
+
215
+ // Convenience version of a common use case of `map`: fetching a property.
216
+ _.pluck = function(obj, key) {
217
+ return _.map(obj, function(value){ return value[key]; });
218
+ };
219
+
220
+ // Return the maximum element or (element-based computation).
221
+ _.max = function(obj, iterator, context) {
222
+ if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
223
+ if (!iterator && _.isEmpty(obj)) return -Infinity;
224
+ var result = {computed : -Infinity};
225
+ each(obj, function(value, index, list) {
226
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
227
+ computed >= result.computed && (result = {value : value, computed : computed});
228
+ });
229
+ return result.value;
230
+ };
231
+
232
+ // Return the minimum element (or element-based computation).
233
+ _.min = function(obj, iterator, context) {
234
+ if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
235
+ if (!iterator && _.isEmpty(obj)) return Infinity;
236
+ var result = {computed : Infinity};
237
+ each(obj, function(value, index, list) {
238
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
239
+ computed < result.computed && (result = {value : value, computed : computed});
240
+ });
241
+ return result.value;
242
+ };
243
+
244
+ // Shuffle an array.
245
+ _.shuffle = function(obj) {
246
+ var shuffled = [], rand;
247
+ each(obj, function(value, index, list) {
248
+ if (index == 0) {
249
+ shuffled[0] = value;
250
+ } else {
251
+ rand = Math.floor(Math.random() * (index + 1));
252
+ shuffled[index] = shuffled[rand];
253
+ shuffled[rand] = value;
254
+ }
255
+ });
256
+ return shuffled;
257
+ };
258
+
259
+ // Sort the object's values by a criterion produced by an iterator.
260
+ _.sortBy = function(obj, iterator, context) {
261
+ return _.pluck(_.map(obj, function(value, index, list) {
262
+ return {
263
+ value : value,
264
+ criteria : iterator.call(context, value, index, list)
265
+ };
266
+ }).sort(function(left, right) {
267
+ var a = left.criteria, b = right.criteria;
268
+ return a < b ? -1 : a > b ? 1 : 0;
269
+ }), 'value');
270
+ };
271
+
272
+ // Groups the object's values by a criterion produced by an iterator
273
+ _.groupBy = function(obj, iterator) {
274
+ var result = {};
275
+ each(obj, function(value, index) {
276
+ var key = iterator(value, index);
277
+ (result[key] || (result[key] = [])).push(value);
278
+ });
279
+ return result;
280
+ };
281
+
282
+ // Use a comparator function to figure out at what index an object should
283
+ // be inserted so as to maintain order. Uses binary search.
284
+ _.sortedIndex = function(array, obj, iterator) {
285
+ iterator || (iterator = _.identity);
286
+ var low = 0, high = array.length;
287
+ while (low < high) {
288
+ var mid = (low + high) >> 1;
289
+ iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
290
+ }
291
+ return low;
292
+ };
293
+
294
+ // Safely convert anything iterable into a real, live array.
295
+ _.toArray = function(iterable) {
296
+ if (!iterable) return [];
297
+ if (iterable.toArray) return iterable.toArray();
298
+ if (_.isArray(iterable)) return slice.call(iterable);
299
+ if (_.isArguments(iterable)) return slice.call(iterable);
300
+ return _.values(iterable);
301
+ };
302
+
303
+ // Return the number of elements in an object.
304
+ _.size = function(obj) {
305
+ return _.toArray(obj).length;
306
+ };
307
+
308
+ // Array Functions
309
+ // ---------------
310
+
311
+ // Get the first element of an array. Passing **n** will return the first N
312
+ // values in the array. Aliased as `head`. The **guard** check allows it to work
313
+ // with `_.map`.
314
+ _.first = _.head = function(array, n, guard) {
315
+ return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
316
+ };
317
+
318
+ // Returns everything but the last entry of the array. Especcialy useful on
319
+ // the arguments object. Passing **n** will return all the values in
320
+ // the array, excluding the last N. The **guard** check allows it to work with
321
+ // `_.map`.
322
+ _.initial = function(array, n, guard) {
323
+ return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
324
+ };
325
+
326
+ // Get the last element of an array. Passing **n** will return the last N
327
+ // values in the array. The **guard** check allows it to work with `_.map`.
328
+ _.last = function(array, n, guard) {
329
+ return (n != null) && !guard ? slice.call(array, array.length - n) : array[array.length - 1];
330
+ };
331
+
332
+ // Returns everything but the first entry of the array. Aliased as `tail`.
333
+ // Especially useful on the arguments object. Passing an **index** will return
334
+ // the rest of the values in the array from that index onward. The **guard**
335
+ // check allows it to work with `_.map`.
336
+ _.rest = _.tail = function(array, index, guard) {
337
+ return slice.call(array, (index == null) || guard ? 1 : index);
338
+ };
339
+
340
+ // Trim out all falsy values from an array.
341
+ _.compact = function(array) {
342
+ return _.filter(array, function(value){ return !!value; });
343
+ };
344
+
345
+ // Return a completely flattened version of an array.
346
+ _.flatten = function(array) {
347
+ return _.reduce(array, function(memo, value) {
348
+ if (_.isArray(value)) return memo.concat(_.flatten(value));
349
+ memo[memo.length] = value;
350
+ return memo;
351
+ }, []);
352
+ };
353
+
354
+ // Return a version of the array that does not contain the specified value(s).
355
+ _.without = function(array) {
356
+ return _.difference(array, slice.call(arguments, 1));
357
+ };
358
+
359
+ // Produce a duplicate-free version of the array. If the array has already
360
+ // been sorted, you have the option of using a faster algorithm.
361
+ // Aliased as `unique`.
362
+ _.uniq = _.unique = function(array, isSorted, iterator) {
363
+ var initial = iterator ? _.map(array, iterator) : array;
364
+ var result = [];
365
+ _.reduce(initial, function(memo, el, i) {
366
+ if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
367
+ memo[memo.length] = el;
368
+ result[result.length] = array[i];
369
+ }
370
+ return memo;
371
+ }, []);
372
+ return result;
373
+ };
374
+
375
+ // Produce an array that contains the union: each distinct element from all of
376
+ // the passed-in arrays.
377
+ _.union = function() {
378
+ return _.uniq(_.flatten(arguments));
379
+ };
380
+
381
+ // Produce an array that contains every item shared between all the
382
+ // passed-in arrays. (Aliased as "intersect" for back-compat.)
383
+ _.intersection = _.intersect = function(array) {
384
+ var rest = slice.call(arguments, 1);
385
+ return _.filter(_.uniq(array), function(item) {
386
+ return _.every(rest, function(other) {
387
+ return _.indexOf(other, item) >= 0;
388
+ });
389
+ });
390
+ };
391
+
392
+ // Take the difference between one array and another.
393
+ // Only the elements present in just the first array will remain.
394
+ _.difference = function(array, other) {
395
+ return _.filter(array, function(value){ return !_.include(other, value); });
396
+ };
397
+
398
+ // Zip together multiple lists into a single array -- elements that share
399
+ // an index go together.
400
+ _.zip = function() {
401
+ var args = slice.call(arguments);
402
+ var length = _.max(_.pluck(args, 'length'));
403
+ var results = new Array(length);
404
+ for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
405
+ return results;
406
+ };
407
+
408
+ // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
409
+ // we need this function. Return the position of the first occurrence of an
410
+ // item in an array, or -1 if the item is not included in the array.
411
+ // Delegates to **ECMAScript 5**'s native `indexOf` if available.
412
+ // If the array is large and already in sort order, pass `true`
413
+ // for **isSorted** to use binary search.
414
+ _.indexOf = function(array, item, isSorted) {
415
+ if (array == null) return -1;
416
+ var i, l;
417
+ if (isSorted) {
418
+ i = _.sortedIndex(array, item);
419
+ return array[i] === item ? i : -1;
420
+ }
421
+ if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
422
+ for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
423
+ return -1;
424
+ };
425
+
426
+ // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
427
+ _.lastIndexOf = function(array, item) {
428
+ if (array == null) return -1;
429
+ if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
430
+ var i = array.length;
431
+ while (i--) if (array[i] === item) return i;
432
+ return -1;
433
+ };
434
+
435
+ // Generate an integer Array containing an arithmetic progression. A port of
436
+ // the native Python `range()` function. See
437
+ // [the Python documentation](http://docs.python.org/library/functions.html#range).
438
+ _.range = function(start, stop, step) {
439
+ if (arguments.length <= 1) {
440
+ stop = start || 0;
441
+ start = 0;
442
+ }
443
+ step = arguments[2] || 1;
444
+
445
+ var len = Math.max(Math.ceil((stop - start) / step), 0);
446
+ var idx = 0;
447
+ var range = new Array(len);
448
+
449
+ while(idx < len) {
450
+ range[idx++] = start;
451
+ start += step;
452
+ }
453
+
454
+ return range;
455
+ };
456
+
457
+ // Function (ahem) Functions
458
+ // ------------------
459
+
460
+ // Create a function bound to a given object (assigning `this`, and arguments,
461
+ // optionally). Binding with arguments is also known as `curry`.
462
+ // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
463
+ // We check for `func.bind` first, to fail fast when `func` is undefined.
464
+ _.bind = function(func, obj) {
465
+ if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
466
+ var args = slice.call(arguments, 2);
467
+ return function() {
468
+ return func.apply(obj, args.concat(slice.call(arguments)));
469
+ };
470
+ };
471
+
472
+ // Bind all of an object's methods to that object. Useful for ensuring that
473
+ // all callbacks defined on an object belong to it.
474
+ _.bindAll = function(obj) {
475
+ var funcs = slice.call(arguments, 1);
476
+ if (funcs.length == 0) funcs = _.functions(obj);
477
+ each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
478
+ return obj;
479
+ };
480
+
481
+ // Memoize an expensive function by storing its results.
482
+ _.memoize = function(func, hasher) {
483
+ var memo = {};
484
+ hasher || (hasher = _.identity);
485
+ return function() {
486
+ var key = hasher.apply(this, arguments);
487
+ return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
488
+ };
489
+ };
490
+
491
+ // Delays a function for the given number of milliseconds, and then calls
492
+ // it with the arguments supplied.
493
+ _.delay = function(func, wait) {
494
+ var args = slice.call(arguments, 2);
495
+ return setTimeout(function(){ return func.apply(func, args); }, wait);
496
+ };
497
+
498
+ // Defers a function, scheduling it to run after the current call stack has
499
+ // cleared.
500
+ _.defer = function(func) {
501
+ return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
502
+ };
503
+
504
+ // Internal function used to implement `_.throttle` and `_.debounce`.
505
+ var limit = function(func, wait, debounce) {
506
+ var timeout;
507
+ return function() {
508
+ var context = this, args = arguments;
509
+ var throttler = function() {
510
+ timeout = null;
511
+ func.apply(context, args);
512
+ };
513
+ if (debounce) clearTimeout(timeout);
514
+ if (debounce || !timeout) timeout = setTimeout(throttler, wait);
515
+ };
516
+ };
517
+
518
+ // Returns a function, that, when invoked, will only be triggered at most once
519
+ // during a given window of time.
520
+ _.throttle = function(func, wait) {
521
+ return limit(func, wait, false);
522
+ };
523
+
524
+ // Returns a function, that, as long as it continues to be invoked, will not
525
+ // be triggered. The function will be called after it stops being called for
526
+ // N milliseconds.
527
+ _.debounce = function(func, wait) {
528
+ return limit(func, wait, true);
529
+ };
530
+
531
+ // Returns a function that will be executed at most one time, no matter how
532
+ // often you call it. Useful for lazy initialization.
533
+ _.once = function(func) {
534
+ var ran = false, memo;
535
+ return function() {
536
+ if (ran) return memo;
537
+ ran = true;
538
+ return memo = func.apply(this, arguments);
539
+ };
540
+ };
541
+
542
+ // Returns the first function passed as an argument to the second,
543
+ // allowing you to adjust arguments, run code before and after, and
544
+ // conditionally execute the original function.
545
+ _.wrap = function(func, wrapper) {
546
+ return function() {
547
+ var args = [func].concat(slice.call(arguments));
548
+ return wrapper.apply(this, args);
549
+ };
550
+ };
551
+
552
+ // Returns a function that is the composition of a list of functions, each
553
+ // consuming the return value of the function that follows.
554
+ _.compose = function() {
555
+ var funcs = slice.call(arguments);
556
+ return function() {
557
+ var args = slice.call(arguments);
558
+ for (var i = funcs.length - 1; i >= 0; i--) {
559
+ args = [funcs[i].apply(this, args)];
560
+ }
561
+ return args[0];
562
+ };
563
+ };
564
+
565
+ // Returns a function that will only be executed after being called N times.
566
+ _.after = function(times, func) {
567
+ return function() {
568
+ if (--times < 1) { return func.apply(this, arguments); }
569
+ };
570
+ };
571
+
572
+ // Object Functions
573
+ // ----------------
574
+
575
+ // Retrieve the names of an object's properties.
576
+ // Delegates to **ECMAScript 5**'s native `Object.keys`
577
+ _.keys = nativeKeys || function(obj) {
578
+ if (obj !== Object(obj)) throw new TypeError('Invalid object');
579
+ var keys = [];
580
+ for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
581
+ return keys;
582
+ };
583
+
584
+ // Retrieve the values of an object's properties.
585
+ _.values = function(obj) {
586
+ return _.map(obj, _.identity);
587
+ };
588
+
589
+ // Return a sorted list of the function names available on the object.
590
+ // Aliased as `methods`
591
+ _.functions = _.methods = function(obj) {
592
+ var names = [];
593
+ for (var key in obj) {
594
+ if (_.isFunction(obj[key])) names.push(key);
595
+ }
596
+ return names.sort();
597
+ };
598
+
599
+ // Extend a given object with all the properties in passed-in object(s).
600
+ _.extend = function(obj) {
601
+ each(slice.call(arguments, 1), function(source) {
602
+ for (var prop in source) {
603
+ if (source[prop] !== void 0) obj[prop] = source[prop];
604
+ }
605
+ });
606
+ return obj;
607
+ };
608
+
609
+ // Fill in a given object with default properties.
610
+ _.defaults = function(obj) {
611
+ each(slice.call(arguments, 1), function(source) {
612
+ for (var prop in source) {
613
+ if (obj[prop] == null) obj[prop] = source[prop];
614
+ }
615
+ });
616
+ return obj;
617
+ };
618
+
619
+ // Create a (shallow-cloned) duplicate of an object.
620
+ _.clone = function(obj) {
621
+ return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
622
+ };
623
+
624
+ // Invokes interceptor with the obj, and then returns obj.
625
+ // The primary purpose of this method is to "tap into" a method chain, in
626
+ // order to perform operations on intermediate results within the chain.
627
+ _.tap = function(obj, interceptor) {
628
+ interceptor(obj);
629
+ return obj;
630
+ };
631
+
632
+ // Internal recursive comparison function.
633
+ function eq(a, b, stack) {
634
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
635
+ // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
636
+ if (a === b) return a !== 0 || 1 / a == 1 / b;
637
+ // A strict comparison is necessary because `null == undefined`.
638
+ if (a == null) return a === b;
639
+ // Compare object types.
640
+ var typeA = typeof a;
641
+ if (typeA != typeof b) return false;
642
+ // Optimization; ensure that both values are truthy or falsy.
643
+ if (!a != !b) return false;
644
+ // `NaN` values are equal.
645
+ if (_.isNaN(a)) return _.isNaN(b);
646
+ // Compare string objects by value.
647
+ var isStringA = _.isString(a), isStringB = _.isString(b);
648
+ if (isStringA || isStringB) return isStringA && isStringB && String(a) == String(b);
649
+ // Compare number objects by value.
650
+ var isNumberA = _.isNumber(a), isNumberB = _.isNumber(b);
651
+ if (isNumberA || isNumberB) return isNumberA && isNumberB && +a == +b;
652
+ // Compare boolean objects by value. The value of `true` is 1; the value of `false` is 0.
653
+ var isBooleanA = _.isBoolean(a), isBooleanB = _.isBoolean(b);
654
+ if (isBooleanA || isBooleanB) return isBooleanA && isBooleanB && +a == +b;
655
+ // Compare dates by their millisecond values.
656
+ var isDateA = _.isDate(a), isDateB = _.isDate(b);
657
+ if (isDateA || isDateB) return isDateA && isDateB && a.getTime() == b.getTime();
658
+ // Compare RegExps by their source patterns and flags.
659
+ var isRegExpA = _.isRegExp(a), isRegExpB = _.isRegExp(b);
660
+ if (isRegExpA || isRegExpB) {
661
+ // Ensure commutative equality for RegExps.
662
+ return isRegExpA && isRegExpB &&
663
+ a.source == b.source &&
664
+ a.global == b.global &&
665
+ a.multiline == b.multiline &&
666
+ a.ignoreCase == b.ignoreCase;
667
+ }
668
+ // Ensure that both values are objects.
669
+ if (typeA != 'object') return false;
670
+ // Unwrap any wrapped objects.
671
+ if (a._chain) a = a._wrapped;
672
+ if (b._chain) b = b._wrapped;
673
+ // Invoke a custom `isEqual` method if one is provided.
674
+ if (_.isFunction(a.isEqual)) return a.isEqual(b);
675
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic structures is
676
+ // adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
677
+ var length = stack.length;
678
+ while (length--) {
679
+ // Linear search. Performance is inversely proportional to the number of unique nested
680
+ // structures.
681
+ if (stack[length] == a) return true;
682
+ }
683
+ // Add the first object to the stack of traversed objects.
684
+ stack.push(a);
685
+ var size = 0, result = true;
686
+ if (a.length === +a.length || b.length === +b.length) {
687
+ // Compare object lengths to determine if a deep comparison is necessary.
688
+ size = a.length;
689
+ result = size == b.length;
690
+ if (result) {
691
+ // Deep compare array-like object contents, ignoring non-numeric properties.
692
+ while (size--) {
693
+ // Ensure commutative equality for sparse arrays.
694
+ if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
695
+ }
696
+ }
697
+ } else {
698
+ // Deep compare objects.
699
+ for (var key in a) {
700
+ if (hasOwnProperty.call(a, key)) {
701
+ // Count the expected number of properties.
702
+ size++;
703
+ // Deep compare each member.
704
+ if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break;
705
+ }
706
+ }
707
+ // Ensure that both objects contain the same number of properties.
708
+ if (result) {
709
+ for (key in b) {
710
+ if (hasOwnProperty.call(b, key) && !size--) break;
711
+ }
712
+ result = !size;
713
+ }
714
+ }
715
+ // Remove the first object from the stack of traversed objects.
716
+ stack.pop();
717
+ return result;
718
+ }
719
+
720
+ // Perform a deep comparison to check if two objects are equal.
721
+ _.isEqual = function(a, b) {
722
+ return eq(a, b, []);
723
+ };
724
+
725
+ // Is a given array or object empty?
726
+ _.isEmpty = function(obj) {
727
+ if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
728
+ for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
729
+ return true;
730
+ };
731
+
732
+ // Is a given value a DOM element?
733
+ _.isElement = function(obj) {
734
+ return !!(obj && obj.nodeType == 1);
735
+ };
736
+
737
+ // Is a given value an array?
738
+ // Delegates to ECMA5's native Array.isArray
739
+ _.isArray = nativeIsArray || function(obj) {
740
+ return toString.call(obj) === '[object Array]';
741
+ };
742
+
743
+ // Is a given variable an object?
744
+ _.isObject = function(obj) {
745
+ return obj === Object(obj);
746
+ };
747
+
748
+ // Is a given variable an arguments object?
749
+ _.isArguments = function(obj) {
750
+ return !!(obj && hasOwnProperty.call(obj, 'callee'));
751
+ };
752
+
753
+ // Is a given value a function?
754
+ _.isFunction = function(obj) {
755
+ return !!(obj && obj.constructor && obj.call && obj.apply);
756
+ };
757
+
758
+ // Is a given value a string?
759
+ _.isString = function(obj) {
760
+ return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
761
+ };
762
+
763
+ // Is a given value a number?
764
+ _.isNumber = function(obj) {
765
+ return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
766
+ };
767
+
768
+ // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
769
+ // that does not equal itself.
770
+ _.isNaN = function(obj) {
771
+ return obj !== obj;
772
+ };
773
+
774
+ // Is a given value a boolean?
775
+ _.isBoolean = function(obj) {
776
+ return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
777
+ };
778
+
779
+ // Is a given value a date?
780
+ _.isDate = function(obj) {
781
+ return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
782
+ };
783
+
784
+ // Is the given value a regular expression?
785
+ _.isRegExp = function(obj) {
786
+ return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
787
+ };
788
+
789
+ // Is a given value equal to null?
790
+ _.isNull = function(obj) {
791
+ return obj === null;
792
+ };
793
+
794
+ // Is a given variable undefined?
795
+ _.isUndefined = function(obj) {
796
+ return obj === void 0;
797
+ };
798
+
799
+ // Utility Functions
800
+ // -----------------
801
+
802
+ // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
803
+ // previous owner. Returns a reference to the Underscore object.
804
+ _.noConflict = function() {
805
+ root._ = previousUnderscore;
806
+ return this;
807
+ };
808
+
809
+ // Keep the identity function around for default iterators.
810
+ _.identity = function(value) {
811
+ return value;
812
+ };
813
+
814
+ // Run a function **n** times.
815
+ _.times = function (n, iterator, context) {
816
+ for (var i = 0; i < n; i++) iterator.call(context, i);
817
+ };
818
+
819
+ // Escape a string for HTML interpolation.
820
+ _.escape = function(string) {
821
+ return (''+string).replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
822
+ };
823
+
824
+ // Add your own custom functions to the Underscore object, ensuring that
825
+ // they're correctly added to the OOP wrapper as well.
826
+ _.mixin = function(obj) {
827
+ each(_.functions(obj), function(name){
828
+ addToWrapper(name, _[name] = obj[name]);
829
+ });
830
+ };
831
+
832
+ // Generate a unique integer id (unique within the entire client session).
833
+ // Useful for temporary DOM ids.
834
+ var idCounter = 0;
835
+ _.uniqueId = function(prefix) {
836
+ var id = idCounter++;
837
+ return prefix ? prefix + id : id;
838
+ };
839
+
840
+ // By default, Underscore uses ERB-style template delimiters, change the
841
+ // following template settings to use alternative delimiters.
842
+ _.templateSettings = {
843
+ evaluate : /<%([\s\S]+?)%>/g,
844
+ interpolate : /<%=([\s\S]+?)%>/g,
845
+ escape : /<%-([\s\S]+?)%>/g
846
+ };
847
+
848
+ // JavaScript micro-templating, similar to John Resig's implementation.
849
+ // Underscore templating handles arbitrary delimiters, preserves whitespace,
850
+ // and correctly escapes quotes within interpolated code.
851
+ _.template = function(str, data) {
852
+ var c = _.templateSettings;
853
+ var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
854
+ 'with(obj||{}){__p.push(\'' +
855
+ str.replace(/\\/g, '\\\\')
856
+ .replace(/'/g, "\\'")
857
+ .replace(c.escape, function(match, code) {
858
+ return "',_.escape(" + code.replace(/\\'/g, "'") + "),'";
859
+ })
860
+ .replace(c.interpolate, function(match, code) {
861
+ return "'," + code.replace(/\\'/g, "'") + ",'";
862
+ })
863
+ .replace(c.evaluate || null, function(match, code) {
864
+ return "');" + code.replace(/\\'/g, "'")
865
+ .replace(/[\r\n\t]/g, ' ') + "__p.push('";
866
+ })
867
+ .replace(/\r/g, '\\r')
868
+ .replace(/\n/g, '\\n')
869
+ .replace(/\t/g, '\\t')
870
+ + "');}return __p.join('');";
871
+ var func = new Function('obj', tmpl);
872
+ return data ? func(data) : func;
873
+ };
874
+
875
+ // The OOP Wrapper
876
+ // ---------------
877
+
878
+ // If Underscore is called as a function, it returns a wrapped object that
879
+ // can be used OO-style. This wrapper holds altered versions of all the
880
+ // underscore functions. Wrapped objects may be chained.
881
+ var wrapper = function(obj) { this._wrapped = obj; };
882
+
883
+ // Expose `wrapper.prototype` as `_.prototype`
884
+ _.prototype = wrapper.prototype;
885
+
886
+ // Helper function to continue chaining intermediate results.
887
+ var result = function(obj, chain) {
888
+ return chain ? _(obj).chain() : obj;
889
+ };
890
+
891
+ // A method to easily add functions to the OOP wrapper.
892
+ var addToWrapper = function(name, func) {
893
+ wrapper.prototype[name] = function() {
894
+ var args = slice.call(arguments);
895
+ unshift.call(args, this._wrapped);
896
+ return result(func.apply(_, args), this._chain);
897
+ };
898
+ };
899
+
900
+ // Add all of the Underscore functions to the wrapper object.
901
+ _.mixin(_);
902
+
903
+ // Add all mutator Array functions to the wrapper.
904
+ each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
905
+ var method = ArrayProto[name];
906
+ wrapper.prototype[name] = function() {
907
+ method.apply(this._wrapped, arguments);
908
+ return result(this._wrapped, this._chain);
909
+ };
910
+ });
911
+
912
+ // Add all accessor Array functions to the wrapper.
913
+ each(['concat', 'join', 'slice'], function(name) {
914
+ var method = ArrayProto[name];
915
+ wrapper.prototype[name] = function() {
916
+ return result(method.apply(this._wrapped, arguments), this._chain);
917
+ };
918
+ });
919
+
920
+ // Start chaining a wrapped Underscore object.
921
+ wrapper.prototype.chain = function() {
922
+ this._chain = true;
923
+ return this;
924
+ };
925
+
926
+ // Extracts the result from a wrapped and chained object.
927
+ wrapper.prototype.value = function() {
928
+ return this._wrapped;
929
+ };
930
+
931
+ })();