ultimate-helpers 0.1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (101) hide show
  1. data/.gitignore +8 -0
  2. data/.rvmrc +1 -0
  3. data/.rvmrc.example +1 -0
  4. data/Gemfile +10 -0
  5. data/Gemfile.lock +126 -0
  6. data/LICENSE +19 -0
  7. data/README.md +25 -0
  8. data/Rakefile +1 -0
  9. data/app/assets/javascripts/ultimate/base.js.coffee +11 -0
  10. data/app/assets/javascripts/ultimate/helpers/asset_tag.js.coffee +82 -0
  11. data/app/assets/javascripts/ultimate/helpers/base.js.coffee +3 -0
  12. data/app/assets/javascripts/ultimate/helpers/decor.js.coffee +19 -0
  13. data/app/assets/javascripts/ultimate/helpers/form_options.js.coffee +106 -0
  14. data/app/assets/javascripts/ultimate/helpers/form_tag.js.coffee +175 -0
  15. data/app/assets/javascripts/ultimate/helpers/javascript.js.coffee +31 -0
  16. data/app/assets/javascripts/ultimate/helpers/number.js.coffee +600 -0
  17. data/app/assets/javascripts/ultimate/helpers/record_tag.js.coffee +81 -0
  18. data/app/assets/javascripts/ultimate/helpers/tag.js.coffee +91 -0
  19. data/app/assets/javascripts/ultimate/helpers/url.js.coffee +152 -0
  20. data/app/assets/javascripts/ultimate/helpers.js.coffee +122 -0
  21. data/app/assets/javascripts/ultimate/jquery.base.js.coffee +85 -0
  22. data/app/assets/javascripts/ultimate/underscore/underscore.inflection.js +176 -0
  23. data/app/assets/javascripts/ultimate/underscore/underscore.js +1204 -0
  24. data/app/assets/javascripts/ultimate/underscore/underscore.outcasts.js.coffee +158 -0
  25. data/app/assets/javascripts/ultimate/underscore/underscore.string.js +600 -0
  26. data/config/routes.rb +2 -0
  27. data/lib/ultimate/helpers/engine.rb +7 -0
  28. data/lib/ultimate/helpers/version.rb +5 -0
  29. data/lib/ultimate/helpers.rb +8 -0
  30. data/scripts/rails +8 -0
  31. data/test/dummy/Rakefile +7 -0
  32. data/test/dummy/_emfile +18 -0
  33. data/test/dummy/app/assets/images/.gitkeep +0 -0
  34. data/test/dummy/app/assets/javascripts/application.js +3 -0
  35. data/test/dummy/app/assets/stylesheets/application.css +13 -0
  36. data/test/dummy/app/assets/stylesheets/global/forms.css.scss +65 -0
  37. data/test/dummy/app/assets/stylesheets/global/layout/footer.scss +18 -0
  38. data/test/dummy/app/assets/stylesheets/global/layout/header.scss +13 -0
  39. data/test/dummy/app/assets/stylesheets/global/layout/main-menu.scss +68 -0
  40. data/test/dummy/app/assets/stylesheets/global/layout.css.scss +46 -0
  41. data/test/dummy/app/assets/stylesheets/global/reserved.css.scss +79 -0
  42. data/test/dummy/app/assets/stylesheets/global/reset.css.scss +85 -0
  43. data/test/dummy/app/assets/stylesheets/global/structures.css.scss +9 -0
  44. data/test/dummy/app/assets/stylesheets/import/base.scss +36 -0
  45. data/test/dummy/app/assets/stylesheets/plugins/qunit.css.scss +3 -0
  46. data/test/dummy/app/controllers/application_controller.rb +4 -0
  47. data/test/dummy/app/controllers/main_controller.rb +8 -0
  48. data/test/dummy/app/helpers/application_helper.rb +2 -0
  49. data/test/dummy/app/mailers/.gitkeep +0 -0
  50. data/test/dummy/app/models/.gitkeep +0 -0
  51. data/test/dummy/app/views/application/_footer.html.haml +3 -0
  52. data/test/dummy/app/views/application/_header.html.haml +4 -0
  53. data/test/dummy/app/views/application/_main_menu.html.haml +11 -0
  54. data/test/dummy/app/views/layouts/application.html.haml +24 -0
  55. data/test/dummy/app/views/main/index.html.haml +13 -0
  56. data/test/dummy/app/views/main/qunit.html.haml +7 -0
  57. data/test/dummy/config/application.rb +58 -0
  58. data/test/dummy/config/boot.rb +10 -0
  59. data/test/dummy/config/database.yml +25 -0
  60. data/test/dummy/config/environment.rb +5 -0
  61. data/test/dummy/config/environments/development.rb +40 -0
  62. data/test/dummy/config/environments/production.rb +67 -0
  63. data/test/dummy/config/environments/test.rb +37 -0
  64. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  65. data/test/dummy/config/initializers/inflections.rb +15 -0
  66. data/test/dummy/config/initializers/mime_types.rb +5 -0
  67. data/test/dummy/config/initializers/qunit-rails.rb +1 -0
  68. data/test/dummy/config/initializers/secret_token.rb +7 -0
  69. data/test/dummy/config/initializers/session_store.rb +8 -0
  70. data/test/dummy/config/initializers/wrap_parameters.rb +14 -0
  71. data/test/dummy/config/locales/en.yml +5 -0
  72. data/test/dummy/config/routes.rb +63 -0
  73. data/test/dummy/config.ru +4 -0
  74. data/test/dummy/log/.gitkeep +0 -0
  75. data/test/dummy/public/404.html +26 -0
  76. data/test/dummy/public/422.html +26 -0
  77. data/test/dummy/public/500.html +25 -0
  78. data/test/dummy/public/favicon.ico +0 -0
  79. data/test/dummy/script/rails +6 -0
  80. data/test/javascripts/all_tests.js.coffee +12 -0
  81. data/test/javascripts/test_helper.js.coffee +3 -0
  82. data/test/javascripts/tests/helpers/asset_tag_test.js.coffee +51 -0
  83. data/test/javascripts/tests/helpers/form_options_test.js.coffee +170 -0
  84. data/test/javascripts/tests/helpers/form_tag_test.js.coffee +226 -0
  85. data/test/javascripts/tests/helpers/javascript_test.js.coffee +25 -0
  86. data/test/javascripts/tests/helpers/number_test.js.coffee +250 -0
  87. data/test/javascripts/tests/helpers/record_tag_test.js.coffee +60 -0
  88. data/test/javascripts/tests/helpers/tag_test.js.coffee +58 -0
  89. data/test/javascripts/tests/helpers/url_test.js.coffee +76 -0
  90. data/test/javascripts/tests/underscore/underscore.outcasts.test.js.coffee +47 -0
  91. data/test/javascripts/vendors/backbone.js +1533 -0
  92. data/test/javascripts/vendors/i18n-lite.js.coffee +20 -0
  93. data/test/stylesheets/test_helper.css +4 -0
  94. data/test/stylesheets/vendors/ultimate/mixins/_routines.scss +120 -0
  95. data/test/stylesheets/vendors/ultimate/mixins/_vendors.scss +44 -0
  96. data/test/stylesheets/vendors/ultimate/mixins/css3/_text-shadow.scss +40 -0
  97. data/test/stylesheets/vendors/ultimate/mixins/css3.scss +350 -0
  98. data/test/stylesheets/vendors/ultimate/mixins/fonts.scss +100 -0
  99. data/test/stylesheets/vendors/ultimate/mixins/microstructures.scss +239 -0
  100. data/ultimate-helpers.gemspec +25 -0
  101. metadata +193 -0
@@ -0,0 +1,1204 @@
1
+ // Underscore.js 1.4.2
2
+ // http://underscorejs.org
3
+ // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
4
+ // Underscore may be freely distributed under the MIT license.
5
+
6
+ (function() {
7
+
8
+ // Baseline setup
9
+ // --------------
10
+
11
+ // Establish the root object, `window` in the browser, or `global` on the server.
12
+ var root = this;
13
+
14
+ // Save the previous value of the `_` variable.
15
+ var previousUnderscore = root._;
16
+
17
+ // Establish the object that gets returned to break out of a loop iteration.
18
+ var breaker = {};
19
+
20
+ // Save bytes in the minified (but not gzipped) version:
21
+ var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
22
+
23
+ // Create quick reference variables for speed access to core prototypes.
24
+ var push = ArrayProto.push,
25
+ slice = ArrayProto.slice,
26
+ concat = ArrayProto.concat,
27
+ unshift = ArrayProto.unshift,
28
+ toString = ObjProto.toString,
29
+ hasOwnProperty = ObjProto.hasOwnProperty;
30
+
31
+ // All **ECMAScript 5** native function implementations that we hope to use
32
+ // are declared here.
33
+ var
34
+ nativeForEach = ArrayProto.forEach,
35
+ nativeMap = ArrayProto.map,
36
+ nativeReduce = ArrayProto.reduce,
37
+ nativeReduceRight = ArrayProto.reduceRight,
38
+ nativeFilter = ArrayProto.filter,
39
+ nativeEvery = ArrayProto.every,
40
+ nativeSome = ArrayProto.some,
41
+ nativeIndexOf = ArrayProto.indexOf,
42
+ nativeLastIndexOf = ArrayProto.lastIndexOf,
43
+ nativeIsArray = Array.isArray,
44
+ nativeKeys = Object.keys,
45
+ nativeBind = FuncProto.bind;
46
+
47
+ // Create a safe reference to the Underscore object for use below.
48
+ var _ = function(obj) {
49
+ if (obj instanceof _) return obj;
50
+ if (!(this instanceof _)) return new _(obj);
51
+ this._wrapped = obj;
52
+ };
53
+
54
+ // Export the Underscore object for **Node.js**, with
55
+ // backwards-compatibility for the old `require()` API. If we're in
56
+ // the browser, add `_` as a global object via a string identifier,
57
+ // for Closure Compiler "advanced" mode.
58
+ if (typeof exports !== 'undefined') {
59
+ if (typeof module !== 'undefined' && module.exports) {
60
+ exports = module.exports = _;
61
+ }
62
+ exports._ = _;
63
+ } else {
64
+ root['_'] = _;
65
+ }
66
+
67
+ // Current version.
68
+ _.VERSION = '1.4.2';
69
+
70
+ // Collection Functions
71
+ // --------------------
72
+
73
+ // The cornerstone, an `each` implementation, aka `forEach`.
74
+ // Handles objects with the built-in `forEach`, arrays, and raw objects.
75
+ // Delegates to **ECMAScript 5**'s native `forEach` if available.
76
+ var each = _.each = _.forEach = function(obj, iterator, context) {
77
+ if (obj == null) return;
78
+ if (nativeForEach && obj.forEach === nativeForEach) {
79
+ obj.forEach(iterator, context);
80
+ } else if (obj.length === +obj.length) {
81
+ for (var i = 0, l = obj.length; i < l; i++) {
82
+ if (iterator.call(context, obj[i], i, obj) === breaker) return;
83
+ }
84
+ } else {
85
+ for (var key in obj) {
86
+ if (_.has(obj, key)) {
87
+ if (iterator.call(context, obj[key], key, obj) === breaker) return;
88
+ }
89
+ }
90
+ }
91
+ };
92
+
93
+ // Return the results of applying the iterator to each element.
94
+ // Delegates to **ECMAScript 5**'s native `map` if available.
95
+ _.map = _.collect = function(obj, iterator, context) {
96
+ var results = [];
97
+ if (obj == null) return results;
98
+ if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
99
+ each(obj, function(value, index, list) {
100
+ results[results.length] = iterator.call(context, value, index, list);
101
+ });
102
+ return results;
103
+ };
104
+
105
+ // **Reduce** builds up a single result from a list of values, aka `inject`,
106
+ // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
107
+ _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
108
+ var initial = arguments.length > 2;
109
+ if (obj == null) obj = [];
110
+ if (nativeReduce && obj.reduce === nativeReduce) {
111
+ if (context) iterator = _.bind(iterator, context);
112
+ return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
113
+ }
114
+ each(obj, function(value, index, list) {
115
+ if (!initial) {
116
+ memo = value;
117
+ initial = true;
118
+ } else {
119
+ memo = iterator.call(context, memo, value, index, list);
120
+ }
121
+ });
122
+ if (!initial) throw new TypeError('Reduce of empty array with no initial value');
123
+ return memo;
124
+ };
125
+
126
+ // The right-associative version of reduce, also known as `foldr`.
127
+ // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
128
+ _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
129
+ var initial = arguments.length > 2;
130
+ if (obj == null) obj = [];
131
+ if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
132
+ if (context) iterator = _.bind(iterator, context);
133
+ return arguments.length > 2 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
134
+ }
135
+ var length = obj.length;
136
+ if (length !== +length) {
137
+ var keys = _.keys(obj);
138
+ length = keys.length;
139
+ }
140
+ each(obj, function(value, index, list) {
141
+ index = keys ? keys[--length] : --length;
142
+ if (!initial) {
143
+ memo = obj[index];
144
+ initial = true;
145
+ } else {
146
+ memo = iterator.call(context, memo, obj[index], index, list);
147
+ }
148
+ });
149
+ if (!initial) throw new TypeError('Reduce of empty array with no initial value');
150
+ return memo;
151
+ };
152
+
153
+ // Return the first value which passes a truth test. Aliased as `detect`.
154
+ _.find = _.detect = function(obj, iterator, context) {
155
+ var result;
156
+ any(obj, function(value, index, list) {
157
+ if (iterator.call(context, value, index, list)) {
158
+ result = value;
159
+ return true;
160
+ }
161
+ });
162
+ return result;
163
+ };
164
+
165
+ // Return all the elements that pass a truth test.
166
+ // Delegates to **ECMAScript 5**'s native `filter` if available.
167
+ // Aliased as `select`.
168
+ _.filter = _.select = function(obj, iterator, context) {
169
+ var results = [];
170
+ if (obj == null) return results;
171
+ if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
172
+ each(obj, function(value, index, list) {
173
+ if (iterator.call(context, value, index, list)) results[results.length] = value;
174
+ });
175
+ return results;
176
+ };
177
+
178
+ // Return all the elements for which a truth test fails.
179
+ _.reject = function(obj, iterator, context) {
180
+ var results = [];
181
+ if (obj == null) return results;
182
+ each(obj, function(value, index, list) {
183
+ if (!iterator.call(context, value, index, list)) results[results.length] = value;
184
+ });
185
+ return results;
186
+ };
187
+
188
+ // Determine whether all of the elements match a truth test.
189
+ // Delegates to **ECMAScript 5**'s native `every` if available.
190
+ // Aliased as `all`.
191
+ _.every = _.all = function(obj, iterator, context) {
192
+ iterator || (iterator = _.identity);
193
+ var result = true;
194
+ if (obj == null) return result;
195
+ if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
196
+ each(obj, function(value, index, list) {
197
+ if (!(result = result && iterator.call(context, value, index, list))) return breaker;
198
+ });
199
+ return !!result;
200
+ };
201
+
202
+ // Determine if at least one element in the object matches a truth test.
203
+ // Delegates to **ECMAScript 5**'s native `some` if available.
204
+ // Aliased as `any`.
205
+ var any = _.some = _.any = function(obj, iterator, context) {
206
+ iterator || (iterator = _.identity);
207
+ var result = false;
208
+ if (obj == null) return result;
209
+ if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
210
+ each(obj, function(value, index, list) {
211
+ if (result || (result = iterator.call(context, value, index, list))) return breaker;
212
+ });
213
+ return !!result;
214
+ };
215
+
216
+ // Determine if the array or object contains a given value (using `===`).
217
+ // Aliased as `include`.
218
+ _.contains = _.include = function(obj, target) {
219
+ var found = false;
220
+ if (obj == null) return found;
221
+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
222
+ found = any(obj, function(value) {
223
+ return value === target;
224
+ });
225
+ return found;
226
+ };
227
+
228
+ // Invoke a method (with arguments) on every item in a collection.
229
+ _.invoke = function(obj, method) {
230
+ var args = slice.call(arguments, 2);
231
+ return _.map(obj, function(value) {
232
+ return (_.isFunction(method) ? method : value[method]).apply(value, args);
233
+ });
234
+ };
235
+
236
+ // Convenience version of a common use case of `map`: fetching a property.
237
+ _.pluck = function(obj, key) {
238
+ return _.map(obj, function(value){ return value[key]; });
239
+ };
240
+
241
+ // Convenience version of a common use case of `filter`: selecting only objects
242
+ // with specific `key:value` pairs.
243
+ _.where = function(obj, attrs) {
244
+ if (_.isEmpty(attrs)) return [];
245
+ return _.filter(obj, function(value) {
246
+ for (var key in attrs) {
247
+ if (attrs[key] !== value[key]) return false;
248
+ }
249
+ return true;
250
+ });
251
+ };
252
+
253
+ // Return the maximum element or (element-based computation).
254
+ // Can't optimize arrays of integers longer than 65,535 elements.
255
+ // See: https://bugs.webkit.org/show_bug.cgi?id=80797
256
+ _.max = function(obj, iterator, context) {
257
+ if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
258
+ return Math.max.apply(Math, obj);
259
+ }
260
+ if (!iterator && _.isEmpty(obj)) return -Infinity;
261
+ var result = {computed : -Infinity};
262
+ each(obj, function(value, index, list) {
263
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
264
+ computed >= result.computed && (result = {value : value, computed : computed});
265
+ });
266
+ return result.value;
267
+ };
268
+
269
+ // Return the minimum element (or element-based computation).
270
+ _.min = function(obj, iterator, context) {
271
+ if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
272
+ return Math.min.apply(Math, obj);
273
+ }
274
+ if (!iterator && _.isEmpty(obj)) return Infinity;
275
+ var result = {computed : Infinity};
276
+ each(obj, function(value, index, list) {
277
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
278
+ computed < result.computed && (result = {value : value, computed : computed});
279
+ });
280
+ return result.value;
281
+ };
282
+
283
+ // Shuffle an array.
284
+ _.shuffle = function(obj) {
285
+ var rand;
286
+ var index = 0;
287
+ var shuffled = [];
288
+ each(obj, function(value) {
289
+ rand = _.random(index++);
290
+ shuffled[index - 1] = shuffled[rand];
291
+ shuffled[rand] = value;
292
+ });
293
+ return shuffled;
294
+ };
295
+
296
+ // An internal function to generate lookup iterators.
297
+ var lookupIterator = function(value) {
298
+ return _.isFunction(value) ? value : function(obj){ return obj[value]; };
299
+ };
300
+
301
+ // Sort the object's values by a criterion produced by an iterator.
302
+ _.sortBy = function(obj, value, context) {
303
+ var iterator = lookupIterator(value);
304
+ return _.pluck(_.map(obj, function(value, index, list) {
305
+ return {
306
+ value : value,
307
+ index : index,
308
+ criteria : iterator.call(context, value, index, list)
309
+ };
310
+ }).sort(function(left, right) {
311
+ var a = left.criteria;
312
+ var b = right.criteria;
313
+ if (a !== b) {
314
+ if (a > b || a === void 0) return 1;
315
+ if (a < b || b === void 0) return -1;
316
+ }
317
+ return left.index < right.index ? -1 : 1;
318
+ }), 'value');
319
+ };
320
+
321
+ // An internal function used for aggregate "group by" operations.
322
+ var group = function(obj, value, context, behavior) {
323
+ var result = {};
324
+ var iterator = lookupIterator(value);
325
+ each(obj, function(value, index) {
326
+ var key = iterator.call(context, value, index, obj);
327
+ behavior(result, key, value);
328
+ });
329
+ return result;
330
+ };
331
+
332
+ // Groups the object's values by a criterion. Pass either a string attribute
333
+ // to group by, or a function that returns the criterion.
334
+ _.groupBy = function(obj, value, context) {
335
+ return group(obj, value, context, function(result, key, value) {
336
+ (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
337
+ });
338
+ };
339
+
340
+ // Counts instances of an object that group by a certain criterion. Pass
341
+ // either a string attribute to count by, or a function that returns the
342
+ // criterion.
343
+ _.countBy = function(obj, value, context) {
344
+ return group(obj, value, context, function(result, key, value) {
345
+ if (!_.has(result, key)) result[key] = 0;
346
+ result[key]++;
347
+ });
348
+ };
349
+
350
+ // Use a comparator function to figure out the smallest index at which
351
+ // an object should be inserted so as to maintain order. Uses binary search.
352
+ _.sortedIndex = function(array, obj, iterator, context) {
353
+ iterator = iterator == null ? _.identity : lookupIterator(iterator);
354
+ var value = iterator.call(context, obj);
355
+ var low = 0, high = array.length;
356
+ while (low < high) {
357
+ var mid = (low + high) >>> 1;
358
+ iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
359
+ }
360
+ return low;
361
+ };
362
+
363
+ // Safely convert anything iterable into a real, live array.
364
+ _.toArray = function(obj) {
365
+ if (!obj) return [];
366
+ if (obj.length === +obj.length) return slice.call(obj);
367
+ return _.values(obj);
368
+ };
369
+
370
+ // Return the number of elements in an object.
371
+ _.size = function(obj) {
372
+ if (obj == null) return 0;
373
+ return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
374
+ };
375
+
376
+ // Array Functions
377
+ // ---------------
378
+
379
+ // Get the first element of an array. Passing **n** will return the first N
380
+ // values in the array. Aliased as `head` and `take`. The **guard** check
381
+ // allows it to work with `_.map`.
382
+ _.first = _.head = _.take = function(array, n, guard) {
383
+ if (array == null) return void 0;
384
+ return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
385
+ };
386
+
387
+ // Returns everything but the last entry of the array. Especially useful on
388
+ // the arguments object. Passing **n** will return all the values in
389
+ // the array, excluding the last N. The **guard** check allows it to work with
390
+ // `_.map`.
391
+ _.initial = function(array, n, guard) {
392
+ return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
393
+ };
394
+
395
+ // Get the last element of an array. Passing **n** will return the last N
396
+ // values in the array. The **guard** check allows it to work with `_.map`.
397
+ _.last = function(array, n, guard) {
398
+ if (array == null) return void 0;
399
+ if ((n != null) && !guard) {
400
+ return slice.call(array, Math.max(array.length - n, 0));
401
+ } else {
402
+ return array[array.length - 1];
403
+ }
404
+ };
405
+
406
+ // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
407
+ // Especially useful on the arguments object. Passing an **n** will return
408
+ // the rest N values in the array. The **guard**
409
+ // check allows it to work with `_.map`.
410
+ _.rest = _.tail = _.drop = function(array, n, guard) {
411
+ return slice.call(array, (n == null) || guard ? 1 : n);
412
+ };
413
+
414
+ // Trim out all falsy values from an array.
415
+ _.compact = function(array) {
416
+ return _.filter(array, function(value){ return !!value; });
417
+ };
418
+
419
+ // Internal implementation of a recursive `flatten` function.
420
+ var flatten = function(input, shallow, output) {
421
+ each(input, function(value) {
422
+ if (_.isArray(value)) {
423
+ shallow ? push.apply(output, value) : flatten(value, shallow, output);
424
+ } else {
425
+ output.push(value);
426
+ }
427
+ });
428
+ return output;
429
+ };
430
+
431
+ // Return a completely flattened version of an array.
432
+ _.flatten = function(array, shallow) {
433
+ return flatten(array, shallow, []);
434
+ };
435
+
436
+ // Return a version of the array that does not contain the specified value(s).
437
+ _.without = function(array) {
438
+ return _.difference(array, slice.call(arguments, 1));
439
+ };
440
+
441
+ // Produce a duplicate-free version of the array. If the array has already
442
+ // been sorted, you have the option of using a faster algorithm.
443
+ // Aliased as `unique`.
444
+ _.uniq = _.unique = function(array, isSorted, iterator, context) {
445
+ var initial = iterator ? _.map(array, iterator, context) : array;
446
+ var results = [];
447
+ var seen = [];
448
+ each(initial, function(value, index) {
449
+ if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
450
+ seen.push(value);
451
+ results.push(array[index]);
452
+ }
453
+ });
454
+ return results;
455
+ };
456
+
457
+ // Produce an array that contains the union: each distinct element from all of
458
+ // the passed-in arrays.
459
+ _.union = function() {
460
+ return _.uniq(concat.apply(ArrayProto, arguments));
461
+ };
462
+
463
+ // Produce an array that contains every item shared between all the
464
+ // passed-in arrays.
465
+ _.intersection = function(array) {
466
+ var rest = slice.call(arguments, 1);
467
+ return _.filter(_.uniq(array), function(item) {
468
+ return _.every(rest, function(other) {
469
+ return _.indexOf(other, item) >= 0;
470
+ });
471
+ });
472
+ };
473
+
474
+ // Take the difference between one array and a number of other arrays.
475
+ // Only the elements present in just the first array will remain.
476
+ _.difference = function(array) {
477
+ var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
478
+ return _.filter(array, function(value){ return !_.contains(rest, value); });
479
+ };
480
+
481
+ // Zip together multiple lists into a single array -- elements that share
482
+ // an index go together.
483
+ _.zip = function() {
484
+ var args = slice.call(arguments);
485
+ var length = _.max(_.pluck(args, 'length'));
486
+ var results = new Array(length);
487
+ for (var i = 0; i < length; i++) {
488
+ results[i] = _.pluck(args, "" + i);
489
+ }
490
+ return results;
491
+ };
492
+
493
+ // Converts lists into objects. Pass either a single array of `[key, value]`
494
+ // pairs, or two parallel arrays of the same length -- one of keys, and one of
495
+ // the corresponding values.
496
+ _.object = function(list, values) {
497
+ if (list == null) return {};
498
+ var result = {};
499
+ for (var i = 0, l = list.length; i < l; i++) {
500
+ if (values) {
501
+ result[list[i]] = values[i];
502
+ } else {
503
+ result[list[i][0]] = list[i][1];
504
+ }
505
+ }
506
+ return result;
507
+ };
508
+
509
+ // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
510
+ // we need this function. Return the position of the first occurrence of an
511
+ // item in an array, or -1 if the item is not included in the array.
512
+ // Delegates to **ECMAScript 5**'s native `indexOf` if available.
513
+ // If the array is large and already in sort order, pass `true`
514
+ // for **isSorted** to use binary search.
515
+ _.indexOf = function(array, item, isSorted) {
516
+ if (array == null) return -1;
517
+ var i = 0, l = array.length;
518
+ if (isSorted) {
519
+ if (typeof isSorted == 'number') {
520
+ i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
521
+ } else {
522
+ i = _.sortedIndex(array, item);
523
+ return array[i] === item ? i : -1;
524
+ }
525
+ }
526
+ if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
527
+ for (; i < l; i++) if (array[i] === item) return i;
528
+ return -1;
529
+ };
530
+
531
+ // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
532
+ _.lastIndexOf = function(array, item, from) {
533
+ if (array == null) return -1;
534
+ var hasIndex = from != null;
535
+ if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
536
+ return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
537
+ }
538
+ var i = (hasIndex ? from : array.length);
539
+ while (i--) if (array[i] === item) return i;
540
+ return -1;
541
+ };
542
+
543
+ // Generate an integer Array containing an arithmetic progression. A port of
544
+ // the native Python `range()` function. See
545
+ // [the Python documentation](http://docs.python.org/library/functions.html#range).
546
+ _.range = function(start, stop, step) {
547
+ if (arguments.length <= 1) {
548
+ stop = start || 0;
549
+ start = 0;
550
+ }
551
+ step = arguments[2] || 1;
552
+
553
+ var len = Math.max(Math.ceil((stop - start) / step), 0);
554
+ var idx = 0;
555
+ var range = new Array(len);
556
+
557
+ while(idx < len) {
558
+ range[idx++] = start;
559
+ start += step;
560
+ }
561
+
562
+ return range;
563
+ };
564
+
565
+ // Function (ahem) Functions
566
+ // ------------------
567
+
568
+ // Reusable constructor function for prototype setting.
569
+ var ctor = function(){};
570
+
571
+ // Create a function bound to a given object (assigning `this`, and arguments,
572
+ // optionally). Binding with arguments is also known as `curry`.
573
+ // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
574
+ // We check for `func.bind` first, to fail fast when `func` is undefined.
575
+ _.bind = function bind(func, context) {
576
+ var bound, args;
577
+ if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
578
+ if (!_.isFunction(func)) throw new TypeError;
579
+ args = slice.call(arguments, 2);
580
+ return bound = function() {
581
+ if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
582
+ ctor.prototype = func.prototype;
583
+ var self = new ctor;
584
+ var result = func.apply(self, args.concat(slice.call(arguments)));
585
+ if (Object(result) === result) return result;
586
+ return self;
587
+ };
588
+ };
589
+
590
+ // Bind all of an object's methods to that object. Useful for ensuring that
591
+ // all callbacks defined on an object belong to it.
592
+ _.bindAll = function(obj) {
593
+ var funcs = slice.call(arguments, 1);
594
+ if (funcs.length == 0) funcs = _.functions(obj);
595
+ each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
596
+ return obj;
597
+ };
598
+
599
+ // Memoize an expensive function by storing its results.
600
+ _.memoize = function(func, hasher) {
601
+ var memo = {};
602
+ hasher || (hasher = _.identity);
603
+ return function() {
604
+ var key = hasher.apply(this, arguments);
605
+ return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
606
+ };
607
+ };
608
+
609
+ // Delays a function for the given number of milliseconds, and then calls
610
+ // it with the arguments supplied.
611
+ _.delay = function(func, wait) {
612
+ var args = slice.call(arguments, 2);
613
+ return setTimeout(function(){ return func.apply(null, args); }, wait);
614
+ };
615
+
616
+ // Defers a function, scheduling it to run after the current call stack has
617
+ // cleared.
618
+ _.defer = function(func) {
619
+ return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
620
+ };
621
+
622
+ // Returns a function, that, when invoked, will only be triggered at most once
623
+ // during a given window of time.
624
+ _.throttle = function(func, wait) {
625
+ var context, args, timeout, throttling, more, result;
626
+ var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
627
+ return function() {
628
+ context = this; args = arguments;
629
+ var later = function() {
630
+ timeout = null;
631
+ if (more) {
632
+ result = func.apply(context, args);
633
+ }
634
+ whenDone();
635
+ };
636
+ if (!timeout) timeout = setTimeout(later, wait);
637
+ if (throttling) {
638
+ more = true;
639
+ } else {
640
+ throttling = true;
641
+ result = func.apply(context, args);
642
+ }
643
+ whenDone();
644
+ return result;
645
+ };
646
+ };
647
+
648
+ // Returns a function, that, as long as it continues to be invoked, will not
649
+ // be triggered. The function will be called after it stops being called for
650
+ // N milliseconds. If `immediate` is passed, trigger the function on the
651
+ // leading edge, instead of the trailing.
652
+ _.debounce = function(func, wait, immediate) {
653
+ var timeout, result;
654
+ return function() {
655
+ var context = this, args = arguments;
656
+ var later = function() {
657
+ timeout = null;
658
+ if (!immediate) result = func.apply(context, args);
659
+ };
660
+ var callNow = immediate && !timeout;
661
+ clearTimeout(timeout);
662
+ timeout = setTimeout(later, wait);
663
+ if (callNow) result = func.apply(context, args);
664
+ return result;
665
+ };
666
+ };
667
+
668
+ // Returns a function that will be executed at most one time, no matter how
669
+ // often you call it. Useful for lazy initialization.
670
+ _.once = function(func) {
671
+ var ran = false, memo;
672
+ return function() {
673
+ if (ran) return memo;
674
+ ran = true;
675
+ memo = func.apply(this, arguments);
676
+ func = null;
677
+ return memo;
678
+ };
679
+ };
680
+
681
+ // Returns the first function passed as an argument to the second,
682
+ // allowing you to adjust arguments, run code before and after, and
683
+ // conditionally execute the original function.
684
+ _.wrap = function(func, wrapper) {
685
+ return function() {
686
+ var args = [func];
687
+ push.apply(args, arguments);
688
+ return wrapper.apply(this, args);
689
+ };
690
+ };
691
+
692
+ // Returns a function that is the composition of a list of functions, each
693
+ // consuming the return value of the function that follows.
694
+ _.compose = function() {
695
+ var funcs = arguments;
696
+ return function() {
697
+ var args = arguments;
698
+ for (var i = funcs.length - 1; i >= 0; i--) {
699
+ args = [funcs[i].apply(this, args)];
700
+ }
701
+ return args[0];
702
+ };
703
+ };
704
+
705
+ // Returns a function that will only be executed after being called N times.
706
+ _.after = function(times, func) {
707
+ if (times <= 0) return func();
708
+ return function() {
709
+ if (--times < 1) {
710
+ return func.apply(this, arguments);
711
+ }
712
+ };
713
+ };
714
+
715
+ // Object Functions
716
+ // ----------------
717
+
718
+ // Retrieve the names of an object's properties.
719
+ // Delegates to **ECMAScript 5**'s native `Object.keys`
720
+ _.keys = nativeKeys || function(obj) {
721
+ if (obj !== Object(obj)) throw new TypeError('Invalid object');
722
+ var keys = [];
723
+ for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
724
+ return keys;
725
+ };
726
+
727
+ // Retrieve the values of an object's properties.
728
+ _.values = function(obj) {
729
+ var values = [];
730
+ for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
731
+ return values;
732
+ };
733
+
734
+ // Convert an object into a list of `[key, value]` pairs.
735
+ _.pairs = function(obj) {
736
+ var pairs = [];
737
+ for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
738
+ return pairs;
739
+ };
740
+
741
+ // Invert the keys and values of an object. The values must be serializable.
742
+ _.invert = function(obj) {
743
+ var result = {};
744
+ for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
745
+ return result;
746
+ };
747
+
748
+ // Return a sorted list of the function names available on the object.
749
+ // Aliased as `methods`
750
+ _.functions = _.methods = function(obj) {
751
+ var names = [];
752
+ for (var key in obj) {
753
+ if (_.isFunction(obj[key])) names.push(key);
754
+ }
755
+ return names.sort();
756
+ };
757
+
758
+ // Extend a given object with all the properties in passed-in object(s).
759
+ _.extend = function(obj) {
760
+ each(slice.call(arguments, 1), function(source) {
761
+ for (var prop in source) {
762
+ obj[prop] = source[prop];
763
+ }
764
+ });
765
+ return obj;
766
+ };
767
+
768
+ // Return a copy of the object only containing the whitelisted properties.
769
+ _.pick = function(obj) {
770
+ var copy = {};
771
+ var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
772
+ each(keys, function(key) {
773
+ if (key in obj) copy[key] = obj[key];
774
+ });
775
+ return copy;
776
+ };
777
+
778
+ // Return a copy of the object without the blacklisted properties.
779
+ _.omit = function(obj) {
780
+ var copy = {};
781
+ var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
782
+ for (var key in obj) {
783
+ if (!_.contains(keys, key)) copy[key] = obj[key];
784
+ }
785
+ return copy;
786
+ };
787
+
788
+ // Fill in a given object with default properties.
789
+ _.defaults = function(obj) {
790
+ each(slice.call(arguments, 1), function(source) {
791
+ for (var prop in source) {
792
+ if (obj[prop] == null) obj[prop] = source[prop];
793
+ }
794
+ });
795
+ return obj;
796
+ };
797
+
798
+ // Create a (shallow-cloned) duplicate of an object.
799
+ _.clone = function(obj) {
800
+ if (!_.isObject(obj)) return obj;
801
+ return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
802
+ };
803
+
804
+ // Invokes interceptor with the obj, and then returns obj.
805
+ // The primary purpose of this method is to "tap into" a method chain, in
806
+ // order to perform operations on intermediate results within the chain.
807
+ _.tap = function(obj, interceptor) {
808
+ interceptor(obj);
809
+ return obj;
810
+ };
811
+
812
+ // Internal recursive comparison function for `isEqual`.
813
+ var eq = function(a, b, aStack, bStack) {
814
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
815
+ // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
816
+ if (a === b) return a !== 0 || 1 / a == 1 / b;
817
+ // A strict comparison is necessary because `null == undefined`.
818
+ if (a == null || b == null) return a === b;
819
+ // Unwrap any wrapped objects.
820
+ if (a instanceof _) a = a._wrapped;
821
+ if (b instanceof _) b = b._wrapped;
822
+ // Compare `[[Class]]` names.
823
+ var className = toString.call(a);
824
+ if (className != toString.call(b)) return false;
825
+ switch (className) {
826
+ // Strings, numbers, dates, and booleans are compared by value.
827
+ case '[object String]':
828
+ // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
829
+ // equivalent to `new String("5")`.
830
+ return a == String(b);
831
+ case '[object Number]':
832
+ // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
833
+ // other numeric values.
834
+ return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
835
+ case '[object Date]':
836
+ case '[object Boolean]':
837
+ // Coerce dates and booleans to numeric primitive values. Dates are compared by their
838
+ // millisecond representations. Note that invalid dates with millisecond representations
839
+ // of `NaN` are not equivalent.
840
+ return +a == +b;
841
+ // RegExps are compared by their source patterns and flags.
842
+ case '[object RegExp]':
843
+ return a.source == b.source &&
844
+ a.global == b.global &&
845
+ a.multiline == b.multiline &&
846
+ a.ignoreCase == b.ignoreCase;
847
+ }
848
+ if (typeof a != 'object' || typeof b != 'object') return false;
849
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
850
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
851
+ var length = aStack.length;
852
+ while (length--) {
853
+ // Linear search. Performance is inversely proportional to the number of
854
+ // unique nested structures.
855
+ if (aStack[length] == a) return bStack[length] == b;
856
+ }
857
+ // Add the first object to the stack of traversed objects.
858
+ aStack.push(a);
859
+ bStack.push(b);
860
+ var size = 0, result = true;
861
+ // Recursively compare objects and arrays.
862
+ if (className == '[object Array]') {
863
+ // Compare array lengths to determine if a deep comparison is necessary.
864
+ size = a.length;
865
+ result = size == b.length;
866
+ if (result) {
867
+ // Deep compare the contents, ignoring non-numeric properties.
868
+ while (size--) {
869
+ if (!(result = eq(a[size], b[size], aStack, bStack))) break;
870
+ }
871
+ }
872
+ } else {
873
+ // Objects with different constructors are not equivalent, but `Object`s
874
+ // from different frames are.
875
+ var aCtor = a.constructor, bCtor = b.constructor;
876
+ if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
877
+ _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
878
+ return false;
879
+ }
880
+ // Deep compare objects.
881
+ for (var key in a) {
882
+ if (_.has(a, key)) {
883
+ // Count the expected number of properties.
884
+ size++;
885
+ // Deep compare each member.
886
+ if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
887
+ }
888
+ }
889
+ // Ensure that both objects contain the same number of properties.
890
+ if (result) {
891
+ for (key in b) {
892
+ if (_.has(b, key) && !(size--)) break;
893
+ }
894
+ result = !size;
895
+ }
896
+ }
897
+ // Remove the first object from the stack of traversed objects.
898
+ aStack.pop();
899
+ bStack.pop();
900
+ return result;
901
+ };
902
+
903
+ // Perform a deep comparison to check if two objects are equal.
904
+ _.isEqual = function(a, b) {
905
+ return eq(a, b, [], []);
906
+ };
907
+
908
+ // Is a given array, string, or object empty?
909
+ // An "empty" object has no enumerable own-properties.
910
+ _.isEmpty = function(obj) {
911
+ if (obj == null) return true;
912
+ if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
913
+ for (var key in obj) if (_.has(obj, key)) return false;
914
+ return true;
915
+ };
916
+
917
+ // Is a given value a DOM element?
918
+ _.isElement = function(obj) {
919
+ return !!(obj && obj.nodeType === 1);
920
+ };
921
+
922
+ // Is a given value an array?
923
+ // Delegates to ECMA5's native Array.isArray
924
+ _.isArray = nativeIsArray || function(obj) {
925
+ return toString.call(obj) == '[object Array]';
926
+ };
927
+
928
+ // Is a given variable an object?
929
+ _.isObject = function(obj) {
930
+ return obj === Object(obj);
931
+ };
932
+
933
+ // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
934
+ each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
935
+ _['is' + name] = function(obj) {
936
+ return toString.call(obj) == '[object ' + name + ']';
937
+ };
938
+ });
939
+
940
+ // Define a fallback version of the method in browsers (ahem, IE), where
941
+ // there isn't any inspectable "Arguments" type.
942
+ if (!_.isArguments(arguments)) {
943
+ _.isArguments = function(obj) {
944
+ return !!(obj && _.has(obj, 'callee'));
945
+ };
946
+ }
947
+
948
+ // Optimize `isFunction` if appropriate.
949
+ if (typeof (/./) !== 'function') {
950
+ _.isFunction = function(obj) {
951
+ return typeof obj === 'function';
952
+ };
953
+ }
954
+
955
+ // Is a given object a finite number?
956
+ _.isFinite = function(obj) {
957
+ return _.isNumber(obj) && isFinite(obj);
958
+ };
959
+
960
+ // Is the given value `NaN`? (NaN is the only number which does not equal itself).
961
+ _.isNaN = function(obj) {
962
+ return _.isNumber(obj) && obj != +obj;
963
+ };
964
+
965
+ // Is a given value a boolean?
966
+ _.isBoolean = function(obj) {
967
+ return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
968
+ };
969
+
970
+ // Is a given value equal to null?
971
+ _.isNull = function(obj) {
972
+ return obj === null;
973
+ };
974
+
975
+ // Is a given variable undefined?
976
+ _.isUndefined = function(obj) {
977
+ return obj === void 0;
978
+ };
979
+
980
+ // Shortcut function for checking if an object has a given property directly
981
+ // on itself (in other words, not on a prototype).
982
+ _.has = function(obj, key) {
983
+ return hasOwnProperty.call(obj, key);
984
+ };
985
+
986
+ // Utility Functions
987
+ // -----------------
988
+
989
+ // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
990
+ // previous owner. Returns a reference to the Underscore object.
991
+ _.noConflict = function() {
992
+ root._ = previousUnderscore;
993
+ return this;
994
+ };
995
+
996
+ // Keep the identity function around for default iterators.
997
+ _.identity = function(value) {
998
+ return value;
999
+ };
1000
+
1001
+ // Run a function **n** times.
1002
+ _.times = function(n, iterator, context) {
1003
+ for (var i = 0; i < n; i++) iterator.call(context, i);
1004
+ };
1005
+
1006
+ // Return a random integer between min and max (inclusive).
1007
+ _.random = function(min, max) {
1008
+ if (max == null) {
1009
+ max = min;
1010
+ min = 0;
1011
+ }
1012
+ return min + (0 | Math.random() * (max - min + 1));
1013
+ };
1014
+
1015
+ // List of HTML entities for escaping.
1016
+ var entityMap = {
1017
+ escape: {
1018
+ '&': '&amp;',
1019
+ '<': '&lt;',
1020
+ '>': '&gt;',
1021
+ '"': '&quot;',
1022
+ "'": '&#x27;',
1023
+ '/': '&#x2F;'
1024
+ }
1025
+ };
1026
+ entityMap.unescape = _.invert(entityMap.escape);
1027
+
1028
+ // Regexes containing the keys and values listed immediately above.
1029
+ var entityRegexes = {
1030
+ escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
1031
+ unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
1032
+ };
1033
+
1034
+ // Functions for escaping and unescaping strings to/from HTML interpolation.
1035
+ _.each(['escape', 'unescape'], function(method) {
1036
+ _[method] = function(string) {
1037
+ if (string == null) return '';
1038
+ return ('' + string).replace(entityRegexes[method], function(match) {
1039
+ return entityMap[method][match];
1040
+ });
1041
+ };
1042
+ });
1043
+
1044
+ // If the value of the named property is a function then invoke it;
1045
+ // otherwise, return it.
1046
+ _.result = function(object, property) {
1047
+ if (object == null) return null;
1048
+ var value = object[property];
1049
+ return _.isFunction(value) ? value.call(object) : value;
1050
+ };
1051
+
1052
+ // Add your own custom functions to the Underscore object.
1053
+ _.mixin = function(obj) {
1054
+ each(_.functions(obj), function(name){
1055
+ var func = _[name] = obj[name];
1056
+ _.prototype[name] = function() {
1057
+ var args = [this._wrapped];
1058
+ push.apply(args, arguments);
1059
+ return result.call(this, func.apply(_, args));
1060
+ };
1061
+ });
1062
+ };
1063
+
1064
+ // Generate a unique integer id (unique within the entire client session).
1065
+ // Useful for temporary DOM ids.
1066
+ var idCounter = 0;
1067
+ _.uniqueId = function(prefix) {
1068
+ var id = idCounter++;
1069
+ return prefix ? prefix + id : id;
1070
+ };
1071
+
1072
+ // By default, Underscore uses ERB-style template delimiters, change the
1073
+ // following template settings to use alternative delimiters.
1074
+ _.templateSettings = {
1075
+ evaluate : /<%([\s\S]+?)%>/g,
1076
+ interpolate : /<%=([\s\S]+?)%>/g,
1077
+ escape : /<%-([\s\S]+?)%>/g
1078
+ };
1079
+
1080
+ // When customizing `templateSettings`, if you don't want to define an
1081
+ // interpolation, evaluation or escaping regex, we need one that is
1082
+ // guaranteed not to match.
1083
+ var noMatch = /(.)^/;
1084
+
1085
+ // Certain characters need to be escaped so that they can be put into a
1086
+ // string literal.
1087
+ var escapes = {
1088
+ "'": "'",
1089
+ '\\': '\\',
1090
+ '\r': 'r',
1091
+ '\n': 'n',
1092
+ '\t': 't',
1093
+ '\u2028': 'u2028',
1094
+ '\u2029': 'u2029'
1095
+ };
1096
+
1097
+ var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
1098
+
1099
+ // JavaScript micro-templating, similar to John Resig's implementation.
1100
+ // Underscore templating handles arbitrary delimiters, preserves whitespace,
1101
+ // and correctly escapes quotes within interpolated code.
1102
+ _.template = function(text, data, settings) {
1103
+ settings = _.defaults({}, settings, _.templateSettings);
1104
+
1105
+ // Combine delimiters into one regular expression via alternation.
1106
+ var matcher = new RegExp([
1107
+ (settings.escape || noMatch).source,
1108
+ (settings.interpolate || noMatch).source,
1109
+ (settings.evaluate || noMatch).source
1110
+ ].join('|') + '|$', 'g');
1111
+
1112
+ // Compile the template source, escaping string literals appropriately.
1113
+ var index = 0;
1114
+ var source = "__p+='";
1115
+ text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
1116
+ source += text.slice(index, offset)
1117
+ .replace(escaper, function(match) { return '\\' + escapes[match]; });
1118
+ source +=
1119
+ escape ? "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'" :
1120
+ interpolate ? "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'" :
1121
+ evaluate ? "';\n" + evaluate + "\n__p+='" : '';
1122
+ index = offset + match.length;
1123
+ });
1124
+ source += "';\n";
1125
+
1126
+ // If a variable is not specified, place data values in local scope.
1127
+ if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
1128
+
1129
+ source = "var __t,__p='',__j=Array.prototype.join," +
1130
+ "print=function(){__p+=__j.call(arguments,'');};\n" +
1131
+ source + "return __p;\n";
1132
+
1133
+ try {
1134
+ var render = new Function(settings.variable || 'obj', '_', source);
1135
+ } catch (e) {
1136
+ e.source = source;
1137
+ throw e;
1138
+ }
1139
+
1140
+ if (data) return render(data, _);
1141
+ var template = function(data) {
1142
+ return render.call(this, data, _);
1143
+ };
1144
+
1145
+ // Provide the compiled function source as a convenience for precompilation.
1146
+ template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
1147
+
1148
+ return template;
1149
+ };
1150
+
1151
+ // Add a "chain" function, which will delegate to the wrapper.
1152
+ _.chain = function(obj) {
1153
+ return _(obj).chain();
1154
+ };
1155
+
1156
+ // OOP
1157
+ // ---------------
1158
+ // If Underscore is called as a function, it returns a wrapped object that
1159
+ // can be used OO-style. This wrapper holds altered versions of all the
1160
+ // underscore functions. Wrapped objects may be chained.
1161
+
1162
+ // Helper function to continue chaining intermediate results.
1163
+ var result = function(obj) {
1164
+ return this._chain ? _(obj).chain() : obj;
1165
+ };
1166
+
1167
+ // Add all of the Underscore functions to the wrapper object.
1168
+ _.mixin(_);
1169
+
1170
+ // Add all mutator Array functions to the wrapper.
1171
+ each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
1172
+ var method = ArrayProto[name];
1173
+ _.prototype[name] = function() {
1174
+ var obj = this._wrapped;
1175
+ method.apply(obj, arguments);
1176
+ if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
1177
+ return result.call(this, obj);
1178
+ };
1179
+ });
1180
+
1181
+ // Add all accessor Array functions to the wrapper.
1182
+ each(['concat', 'join', 'slice'], function(name) {
1183
+ var method = ArrayProto[name];
1184
+ _.prototype[name] = function() {
1185
+ return result.call(this, method.apply(this._wrapped, arguments));
1186
+ };
1187
+ });
1188
+
1189
+ _.extend(_.prototype, {
1190
+
1191
+ // Start chaining a wrapped Underscore object.
1192
+ chain: function() {
1193
+ this._chain = true;
1194
+ return this;
1195
+ },
1196
+
1197
+ // Extracts the result from a wrapped and chained object.
1198
+ value: function() {
1199
+ return this._wrapped;
1200
+ }
1201
+
1202
+ });
1203
+
1204
+ }).call(this);