kojac 0.9.0

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