backbonejs-rails 0.0.5 → 0.0.6

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,9 +1,11 @@
1
- (function(i){var n=function(){var f=function(){};f.prototype={otag:"{{",ctag:"}}",pragmas:{},buffer:[],pragmas_implemented:{"IMPLICIT-ITERATOR":true},context:{},render:function(a,b,c,d){if(!d){this.context=b;this.buffer=[]}if(!this.includes("",a))if(d)return a;else{this.send(a);return}a=this.render_pragmas(a);a=this.render_section(a,b,c);if(d)return this.render_tags(a,b,c,d);this.render_tags(a,b,c,d)},send:function(a){a!=""&&this.buffer.push(a)},render_pragmas:function(a){if(!this.includes("%",a))return a;
2
- var b=this;return a.replace(RegExp(this.otag+"%([\\w-]+) ?([\\w]+=[\\w]+)?"+this.ctag),function(c,d,e){if(!b.pragmas_implemented[d])throw{message:"This implementation of mustache doesn't understand the '"+d+"' pragma"};b.pragmas[d]={};if(e){c=e.split("=");b.pragmas[d][c[0]]=c[1]}return""})},render_partial:function(a,b,c){a=this.trim(a);if(!c||c[a]===undefined)throw{message:"unknown_partial '"+a+"'"};if(typeof b[a]!="object")return this.render(c[a],b,c,true);return this.render(c[a],b[a],c,true)},render_section:function(a,
3
- b,c){if(!this.includes("#",a)&&!this.includes("^",a))return a;var d=this;return a.replace(RegExp(this.otag+"(\\^|\\#)\\s*(.+)\\s*"+this.ctag+"\n*([\\s\\S]+?)"+this.otag+"\\/\\s*\\2\\s*"+this.ctag+"\\s*","mg"),function(e,j,k,h){e=d.find(k,b);if(j=="^")return!e||d.is_array(e)&&e.length===0?d.render(h,b,c,true):"";else if(j=="#")return d.is_array(e)?d.map(e,function(g){return d.render(h,d.create_context(g),c,true)}).join(""):d.is_object(e)?d.render(h,d.create_context(e),c,true):typeof e==="function"?
4
- e.call(b,h,function(g){return d.render(g,b,c,true)}):e?d.render(h,b,c,true):""})},render_tags:function(a,b,c,d){var e=this,j=function(){return RegExp(e.otag+"(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?"+e.ctag+"+","g")},k=j(),h=function(o,m,l){switch(m){case "!":return"";case "=":e.set_delimiters(l);k=j();return"";case ">":return e.render_partial(l,b,c);case "{":return e.find(l,b);default:return e.escape(e.find(l,b))}};a=a.split("\n");for(var g=0;g<a.length;g++){a[g]=a[g].replace(k,h,this);d||this.send(a[g])}if(d)return a.join("\n")},
5
- set_delimiters:function(a){a=a.split(" ");this.otag=this.escape_regex(a[0]);this.ctag=this.escape_regex(a[1])},escape_regex:function(a){if(!arguments.callee.sRE)arguments.callee.sRE=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\)","g");return a.replace(arguments.callee.sRE,"\\$1")},find:function(a,b){a=this.trim(a);var c;if(b[a]===false||b[a]===0||b[a])c=b[a];else if(this.context[a]===false||this.context[a]===0||this.context[a])c=this.context[a];if(typeof c==="function")return c.apply(b);
6
- if(c!==undefined)return c;return""},includes:function(a,b){return b.indexOf(this.otag+a)!=-1},escape:function(a){a=String(a===null?"":a);return a.replace(/&(?!\w+;)|["<>\\]/g,function(b){switch(b){case "&":return"&amp;";case "\\":return"\\\\";case '"':return'"';case "<":return"&lt;";case ">":return"&gt;";default:return b}})},create_context:function(a){if(this.is_object(a))return a;else{var b=".";if(this.pragmas["IMPLICIT-ITERATOR"])b=this.pragmas["IMPLICIT-ITERATOR"].iterator;var c={};c[b]=a;return c}},
7
- is_object:function(a){return a&&typeof a=="object"},is_array:function(a){return Object.prototype.toString.call(a)==="[object Array]"},trim:function(a){return a.replace(/^\s*|\s*$/g,"")},map:function(a,b){if(typeof a.map=="function")return a.map(b);else{for(var c=[],d=a.length,e=0;e<d;e++)c.push(b(a[e]));return c}}};return{name:"mustache.js",version:"0.3.0",to_html:function(a,b,c,d){var e=new f;if(d)e.send=d;e.render(a,b,c);if(!d)return e.buffer.join("\n")}}}();window.ich=new function(){var f=this;
8
- f.VERSION="0.9";f.templates={};f.partials={};f.addTemplate=function(a,b){if(f[a])throw"Invalid name: "+a+".";if(f.templates[a])throw'Template " + name + " exists';f.templates[a]=b;f[a]=function(c,d){c=c||{};var e=n.to_html(f.templates[a],c,f.partials);return d?e:i(e)}};f.addPartial=function(a,b){if(f.partials[a])throw'Partial " + name + " exists';else f.partials[a]=b};f.grabTemplates=function(){i('script[type="text/html"]').each(function(a,b){var c=i(typeof a==="number"?b:a),d="".trim?c.html().trim():
9
- i.trim(c.html());f[c.hasClass("partial")?"addPartial":"addTemplate"](c.attr("id"),d);c.remove()})};f.clearAll=function(){for(var a in f.templates)delete f[a];f.templates={};f.partials={}};f.refresh=function(){f.clearAll();f.grabTemplates()}};i(function(){ich.grabTemplates()})})(window.jQuery||window.Zepto);
1
+ (function(){var q=function(){function c(a){return(""+a).replace(/&(?!\w+;)|[<>"']/g,function(a){return k[a]||a})}var e=Object.prototype.toString;Array.isArray=Array.isArray||function(a){return"[object Array]"==e.call(a)};var i=String.prototype.trim,g;if(i)g=function(a){return null==a?"":i.call(a)};else{var h,m;/\S/.test("\u00a0")?(h=/^[\s\xA0]+/,m=/[\s\xA0]+$/):(h=/^\s+/,m=/\s+$/);g=function(a){return null==a?"":a.toString().replace(h,"").replace(m,"")}}var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;",
2
+ "'":"&#39;"},o={},p=function(){};p.prototype={otag:"{{",ctag:"}}",pragmas:{},buffer:[],pragmas_implemented:{"IMPLICIT-ITERATOR":!0},context:{},render:function(a,d,b,f){if(!f)this.context=d,this.buffer=[];if(this.includes("",a)){var a=this.render_pragmas(a),j=this.render_section(a,d,b);!1===j&&(j=this.render_tags(a,d,b,f));if(f)return j;this.sendLines(j)}else{if(f)return a;this.send(a)}},send:function(a){""!==a&&this.buffer.push(a)},sendLines:function(a){if(a)for(var a=a.split("\n"),d=0;d<a.length;d++)this.send(a[d])},
3
+ render_pragmas:function(a){if(!this.includes("%",a))return a;var d=this,b=this.getCachedRegex("render_pragmas",function(a,d){return RegExp(a+"%([\\w-]+) ?([\\w]+=[\\w]+)?"+d,"g")});return a.replace(b,function(a,b,e){if(!d.pragmas_implemented[b])throw{message:"This implementation of mustache doesn't understand the '"+b+"' pragma"};d.pragmas[b]={};e&&(a=e.split("="),d.pragmas[b][a[0]]=a[1]);return""})},render_partial:function(a,d,b){a=g(a);if(!b||void 0===b[a])throw{message:"unknown_partial '"+a+"'"};
4
+ return!d||"object"!=typeof d[a]?this.render(b[a],d,b,!0):this.render(b[a],d[a],b,!0)},render_section:function(a,d,b){if(!this.includes("#",a)&&!this.includes("^",a))return!1;var f=this,j=this.getCachedRegex("render_section",function(a,b){return RegExp("^([\\s\\S]*?)"+a+"(\\^|\\#)\\s*(.+)\\s*"+b+"\n*([\\s\\S]*?)"+a+"\\/\\s*\\3\\s*"+b+"\\s*([\\s\\S]*)$","g")});return a.replace(j,function(a,j,e,c,g,h){var a=j?f.render_tags(j,d,b,!0):"",h=h?f.render(h,d,b,!0):"",n,c=f.find(c,d);"^"===e?n=!c||Array.isArray(c)&&
5
+ 0===c.length?f.render(g,d,b,!0):"":"#"===e&&(n=Array.isArray(c)?f.map(c,function(a){return f.render(g,f.create_context(a),b,!0)}).join(""):f.is_object(c)?f.render(g,f.create_context(c),b,!0):"function"==typeof c?c.call(d,g,function(a){return f.render(a,d,b,!0)}):c?f.render(g,d,b,!0):"");return a+n+h})},render_tags:function(a,d,b,f){for(var j=this,e=function(){return j.getCachedRegex("render_tags",function(a,b){return RegExp(a+"(=|!|>|&|\\{|%)?([^#\\^]+?)\\1?"+b+"+","g")})},g=e(),h=function(a,f,h){switch(f){case "!":return"";
6
+ case "=":return j.set_delimiters(h),g=e(),"";case ">":return j.render_partial(h,d,b);case "{":case "&":return j.find(h,d);default:return c(j.find(h,d))}},a=a.split("\n"),i=0;i<a.length;i++)a[i]=a[i].replace(g,h,this),f||this.send(a[i]);if(f)return a.join("\n")},set_delimiters:function(a){a=a.split(" ");this.otag=this.escape_regex(a[0]);this.ctag=this.escape_regex(a[1])},escape_regex:function(a){if(!arguments.callee.sRE)arguments.callee.sRE=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\)",
7
+ "g");return a.replace(arguments.callee.sRE,"\\$1")},find:function(a,d){function b(a){return!1===a||0===a||a}var a=g(a),f;if(a.match(/([a-z_]+)\./ig)){var c=this.walk_context(a,d);b(c)&&(f=c)}else b(d[a])?f=d[a]:b(this.context[a])&&(f=this.context[a]);return"function"==typeof f?f.apply(d):void 0!==f?f:""},walk_context:function(a,d){for(var b=a.split("."),f=void 0!=d[b[0]]?d:this.context,c=f[b.shift()];void 0!=c&&0<b.length;)f=c,c=c[b.shift()];return"function"==typeof c?c.apply(f):c},includes:function(a,
8
+ d){return-1!=d.indexOf(this.otag+a)},create_context:function(a){if(this.is_object(a))return a;var d=".";if(this.pragmas["IMPLICIT-ITERATOR"])d=this.pragmas["IMPLICIT-ITERATOR"].iterator;var b={};b[d]=a;return b},is_object:function(a){return a&&"object"==typeof a},map:function(a,d){if("function"==typeof a.map)return a.map(d);for(var b=[],c=a.length,e=0;e<c;e++)b.push(d(a[e]));return b},getCachedRegex:function(a,d){var b=o[this.otag];b||(b=o[this.otag]={});var c=b[this.ctag];c||(c=b[this.ctag]={});
9
+ (b=c[a])||(b=c[a]=d(this.otag,this.ctag));return b}};return{name:"mustache.js",version:"0.4.0",to_html:function(a,c,b,f){var e=new p;if(f)e.send=f;e.render(a,c||{},b);if(!f)return e.buffer.join("\n")}}}();(function(){var c={VERSION:"0.10",templates:{},$:"undefined"!==typeof window?window.jQuery||window.Zepto||null:null,addTemplate:function(e,i){if("object"===typeof e)for(var g in e)this.addTemplate(g,e[g]);else c[e]?console.error("Invalid name: "+e+"."):c.templates[e]?console.error('Template "'+e+
10
+ ' " exists'):(c.templates[e]=i,c[e]=function(g,i){var g=g||{},k=q.to_html(c.templates[e],g,c.templates);return c.$&&!i?c.$(k):k})},clearAll:function(){for(var e in c.templates)delete c[e];c.templates={}},refresh:function(){c.clearAll();c.grabTemplates()},grabTemplates:function(){var e,i=document.getElementsByTagName("script"),g,h=[];for(e=0,l=i.length;e<l;e++)if((g=i[e])&&g.innerHTML&&g.id&&("text/html"===g.type||"text/x-icanhaz"===g.type))c.addTemplate(g.id,"".trim?g.innerHTML.trim():g.innerHTML.replace(/^\s+/,
11
+ "").replace(/\s+$/,"")),h.unshift(g);for(e=0,l=h.length;e<l;e++)h[e].parentNode.removeChild(h[e])}};"undefined"!==typeof require?module.exports=c:window.ich=c;"undefined"!==typeof document&&(c.$?c.$(function(){c.grabTemplates()}):document.addEventListener("DOMContentLoaded",function(){c.grabTemplates()},!0))})()})();
@@ -1,5 +1,5 @@
1
- // Underscore.js 1.1.7
2
- // (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
1
+ // Underscore.js 1.3.1
2
+ // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
3
3
  // Underscore is freely distributable under the MIT license.
4
4
  // Portions of Underscore are inspired or borrowed from Prototype,
5
5
  // Oliver Steele's Functional, and John Resig's Micro-Templating.
@@ -48,19 +48,21 @@
48
48
  // Create a safe reference to the Underscore object for use below.
49
49
  var _ = function(obj) { return new wrapper(obj); };
50
50
 
51
- // Export the Underscore object for **CommonJS**, with backwards-compatibility
52
- // for the old `require()` API. If we're not in CommonJS, add `_` to the
53
- // global object.
54
- if (typeof module !== 'undefined' && module.exports) {
55
- module.exports = _;
56
- _._ = _;
51
+ // Export the Underscore object for **Node.js**, with
52
+ // backwards-compatibility for the old `require()` API. If we're in
53
+ // the browser, add `_` as a global object via a string identifier,
54
+ // for Closure Compiler "advanced" mode.
55
+ if (typeof exports !== 'undefined') {
56
+ if (typeof module !== 'undefined' && module.exports) {
57
+ exports = module.exports = _;
58
+ }
59
+ exports._ = _;
57
60
  } else {
58
- // Exported as a string, for Closure Compiler "advanced" mode.
59
61
  root['_'] = _;
60
62
  }
61
63
 
62
64
  // Current version.
63
- _.VERSION = '1.1.7';
65
+ _.VERSION = '1.3.1';
64
66
 
65
67
  // Collection Functions
66
68
  // --------------------
@@ -78,7 +80,7 @@
78
80
  }
79
81
  } else {
80
82
  for (var key in obj) {
81
- if (hasOwnProperty.call(obj, key)) {
83
+ if (_.has(obj, key)) {
82
84
  if (iterator.call(context, obj[key], key, obj) === breaker) return;
83
85
  }
84
86
  }
@@ -87,20 +89,21 @@
87
89
 
88
90
  // Return the results of applying the iterator to each element.
89
91
  // Delegates to **ECMAScript 5**'s native `map` if available.
90
- _.map = function(obj, iterator, context) {
92
+ _.map = _.collect = function(obj, iterator, context) {
91
93
  var results = [];
92
94
  if (obj == null) return results;
93
95
  if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
94
96
  each(obj, function(value, index, list) {
95
97
  results[results.length] = iterator.call(context, value, index, list);
96
98
  });
99
+ if (obj.length === +obj.length) results.length = obj.length;
97
100
  return results;
98
101
  };
99
102
 
100
103
  // **Reduce** builds up a single result from a list of values, aka `inject`,
101
104
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
102
105
  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
103
- var initial = memo !== void 0;
106
+ var initial = arguments.length > 2;
104
107
  if (obj == null) obj = [];
105
108
  if (nativeReduce && obj.reduce === nativeReduce) {
106
109
  if (context) iterator = _.bind(iterator, context);
@@ -114,20 +117,22 @@
114
117
  memo = iterator.call(context, memo, value, index, list);
115
118
  }
116
119
  });
117
- if (!initial) throw new TypeError("Reduce of empty array with no initial value");
120
+ if (!initial) throw new TypeError('Reduce of empty array with no initial value');
118
121
  return memo;
119
122
  };
120
123
 
121
124
  // The right-associative version of reduce, also known as `foldr`.
122
125
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
123
126
  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
127
+ var initial = arguments.length > 2;
124
128
  if (obj == null) obj = [];
125
129
  if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
126
130
  if (context) iterator = _.bind(iterator, context);
127
- return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
131
+ return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
128
132
  }
129
- var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
130
- return _.reduce(reversed, iterator, memo, context);
133
+ var reversed = _.toArray(obj).reverse();
134
+ if (context && !initial) iterator = _.bind(iterator, context);
135
+ return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
131
136
  };
132
137
 
133
138
  // Return the first value which passes a truth test. Aliased as `detect`.
@@ -182,12 +187,12 @@
182
187
  // Delegates to **ECMAScript 5**'s native `some` if available.
183
188
  // Aliased as `any`.
184
189
  var any = _.some = _.any = function(obj, iterator, context) {
185
- iterator = iterator || _.identity;
190
+ iterator || (iterator = _.identity);
186
191
  var result = false;
187
192
  if (obj == null) return result;
188
193
  if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
189
194
  each(obj, function(value, index, list) {
190
- if (result |= iterator.call(context, value, index, list)) return breaker;
195
+ if (result || (result = iterator.call(context, value, index, list))) return breaker;
191
196
  });
192
197
  return !!result;
193
198
  };
@@ -198,8 +203,8 @@
198
203
  var found = false;
199
204
  if (obj == null) return found;
200
205
  if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
201
- any(obj, function(value) {
202
- if (found = value === target) return true;
206
+ found = any(obj, function(value) {
207
+ return value === target;
203
208
  });
204
209
  return found;
205
210
  };
@@ -208,7 +213,7 @@
208
213
  _.invoke = function(obj, method) {
209
214
  var args = slice.call(arguments, 2);
210
215
  return _.map(obj, function(value) {
211
- return (method.call ? method || value : value[method]).apply(value, args);
216
+ return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
212
217
  });
213
218
  };
214
219
 
@@ -220,6 +225,7 @@
220
225
  // Return the maximum element or (element-based computation).
221
226
  _.max = function(obj, iterator, context) {
222
227
  if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
228
+ if (!iterator && _.isEmpty(obj)) return -Infinity;
223
229
  var result = {computed : -Infinity};
224
230
  each(obj, function(value, index, list) {
225
231
  var computed = iterator ? iterator.call(context, value, index, list) : value;
@@ -231,6 +237,7 @@
231
237
  // Return the minimum element (or element-based computation).
232
238
  _.min = function(obj, iterator, context) {
233
239
  if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
240
+ if (!iterator && _.isEmpty(obj)) return Infinity;
234
241
  var result = {computed : Infinity};
235
242
  each(obj, function(value, index, list) {
236
243
  var computed = iterator ? iterator.call(context, value, index, list) : value;
@@ -239,6 +246,21 @@
239
246
  return result.value;
240
247
  };
241
248
 
249
+ // Shuffle an array.
250
+ _.shuffle = function(obj) {
251
+ var shuffled = [], rand;
252
+ each(obj, function(value, index, list) {
253
+ if (index == 0) {
254
+ shuffled[0] = value;
255
+ } else {
256
+ rand = Math.floor(Math.random() * (index + 1));
257
+ shuffled[index] = shuffled[rand];
258
+ shuffled[rand] = value;
259
+ }
260
+ });
261
+ return shuffled;
262
+ };
263
+
242
264
  // Sort the object's values by a criterion produced by an iterator.
243
265
  _.sortBy = function(obj, iterator, context) {
244
266
  return _.pluck(_.map(obj, function(value, index, list) {
@@ -252,9 +274,11 @@
252
274
  }), 'value');
253
275
  };
254
276
 
255
- // Groups the object's values by a criterion produced by an iterator
256
- _.groupBy = function(obj, iterator) {
277
+ // Groups the object's values by a criterion. Pass either a string attribute
278
+ // to group by, or a function that returns the criterion.
279
+ _.groupBy = function(obj, val) {
257
280
  var result = {};
281
+ var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
258
282
  each(obj, function(value, index) {
259
283
  var key = iterator(value, index);
260
284
  (result[key] || (result[key] = [])).push(value);
@@ -298,6 +322,24 @@
298
322
  return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
299
323
  };
300
324
 
325
+ // Returns everything but the last entry of the array. Especcialy useful on
326
+ // the arguments object. Passing **n** will return all the values in
327
+ // the array, excluding the last N. The **guard** check allows it to work with
328
+ // `_.map`.
329
+ _.initial = function(array, n, guard) {
330
+ return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
331
+ };
332
+
333
+ // Get the last element of an array. Passing **n** will return the last N
334
+ // values in the array. The **guard** check allows it to work with `_.map`.
335
+ _.last = function(array, n, guard) {
336
+ if ((n != null) && !guard) {
337
+ return slice.call(array, Math.max(array.length - n, 0));
338
+ } else {
339
+ return array[array.length - 1];
340
+ }
341
+ };
342
+
301
343
  // Returns everything but the first entry of the array. Aliased as `tail`.
302
344
  // Especially useful on the arguments object. Passing an **index** will return
303
345
  // the rest of the values in the array from that index onward. The **guard**
@@ -306,20 +348,15 @@
306
348
  return slice.call(array, (index == null) || guard ? 1 : index);
307
349
  };
308
350
 
309
- // Get the last element of an array.
310
- _.last = function(array) {
311
- return array[array.length - 1];
312
- };
313
-
314
351
  // Trim out all falsy values from an array.
315
352
  _.compact = function(array) {
316
353
  return _.filter(array, function(value){ return !!value; });
317
354
  };
318
355
 
319
356
  // Return a completely flattened version of an array.
320
- _.flatten = function(array) {
357
+ _.flatten = function(array, shallow) {
321
358
  return _.reduce(array, function(memo, value) {
322
- if (_.isArray(value)) return memo.concat(_.flatten(value));
359
+ if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
323
360
  memo[memo.length] = value;
324
361
  return memo;
325
362
  }, []);
@@ -333,17 +370,23 @@
333
370
  // Produce a duplicate-free version of the array. If the array has already
334
371
  // been sorted, you have the option of using a faster algorithm.
335
372
  // Aliased as `unique`.
336
- _.uniq = _.unique = function(array, isSorted) {
337
- return _.reduce(array, function(memo, el, i) {
338
- if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
373
+ _.uniq = _.unique = function(array, isSorted, iterator) {
374
+ var initial = iterator ? _.map(array, iterator) : array;
375
+ var result = [];
376
+ _.reduce(initial, function(memo, el, i) {
377
+ if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
378
+ memo[memo.length] = el;
379
+ result[result.length] = array[i];
380
+ }
339
381
  return memo;
340
382
  }, []);
383
+ return result;
341
384
  };
342
385
 
343
386
  // Produce an array that contains the union: each distinct element from all of
344
387
  // the passed-in arrays.
345
388
  _.union = function() {
346
- return _.uniq(_.flatten(arguments));
389
+ return _.uniq(_.flatten(arguments, true));
347
390
  };
348
391
 
349
392
  // Produce an array that contains every item shared between all the
@@ -357,10 +400,11 @@
357
400
  });
358
401
  };
359
402
 
360
- // Take the difference between one array and another.
403
+ // Take the difference between one array and a number of other arrays.
361
404
  // Only the elements present in just the first array will remain.
362
- _.difference = function(array, other) {
363
- return _.filter(array, function(value){ return !_.include(other, value); });
405
+ _.difference = function(array) {
406
+ var rest = _.flatten(slice.call(arguments, 1));
407
+ return _.filter(array, function(value){ return !_.include(rest, value); });
364
408
  };
365
409
 
366
410
  // Zip together multiple lists into a single array -- elements that share
@@ -387,17 +431,16 @@
387
431
  return array[i] === item ? i : -1;
388
432
  }
389
433
  if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
390
- for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
434
+ for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
391
435
  return -1;
392
436
  };
393
437
 
394
-
395
438
  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
396
439
  _.lastIndexOf = function(array, item) {
397
440
  if (array == null) return -1;
398
441
  if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
399
442
  var i = array.length;
400
- while (i--) if (array[i] === item) return i;
443
+ while (i--) if (i in array && array[i] === item) return i;
401
444
  return -1;
402
445
  };
403
446
 
@@ -426,15 +469,25 @@
426
469
  // Function (ahem) Functions
427
470
  // ------------------
428
471
 
472
+ // Reusable constructor function for prototype setting.
473
+ var ctor = function(){};
474
+
429
475
  // Create a function bound to a given object (assigning `this`, and arguments,
430
476
  // optionally). Binding with arguments is also known as `curry`.
431
477
  // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
432
478
  // We check for `func.bind` first, to fail fast when `func` is undefined.
433
- _.bind = function(func, obj) {
479
+ _.bind = function bind(func, context) {
480
+ var bound, args;
434
481
  if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
435
- var args = slice.call(arguments, 2);
436
- return function() {
437
- return func.apply(obj, args.concat(slice.call(arguments)));
482
+ if (!_.isFunction(func)) throw new TypeError;
483
+ args = slice.call(arguments, 2);
484
+ return bound = function() {
485
+ if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
486
+ ctor.prototype = func.prototype;
487
+ var self = new ctor;
488
+ var result = func.apply(self, args.concat(slice.call(arguments)));
489
+ if (Object(result) === result) return result;
490
+ return self;
438
491
  };
439
492
  };
440
493
 
@@ -453,7 +506,7 @@
453
506
  hasher || (hasher = _.identity);
454
507
  return function() {
455
508
  var key = hasher.apply(this, arguments);
456
- return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
509
+ return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
457
510
  };
458
511
  };
459
512
 
@@ -470,31 +523,43 @@
470
523
  return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
471
524
  };
472
525
 
473
- // Internal function used to implement `_.throttle` and `_.debounce`.
474
- var limit = function(func, wait, debounce) {
475
- var timeout;
526
+ // Returns a function, that, when invoked, will only be triggered at most once
527
+ // during a given window of time.
528
+ _.throttle = function(func, wait) {
529
+ var context, args, timeout, throttling, more;
530
+ var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
476
531
  return function() {
477
- var context = this, args = arguments;
478
- var throttler = function() {
532
+ context = this; args = arguments;
533
+ var later = function() {
479
534
  timeout = null;
480
- func.apply(context, args);
535
+ if (more) func.apply(context, args);
536
+ whenDone();
481
537
  };
482
- if (debounce) clearTimeout(timeout);
483
- if (debounce || !timeout) timeout = setTimeout(throttler, wait);
538
+ if (!timeout) timeout = setTimeout(later, wait);
539
+ if (throttling) {
540
+ more = true;
541
+ } else {
542
+ func.apply(context, args);
543
+ }
544
+ whenDone();
545
+ throttling = true;
484
546
  };
485
547
  };
486
548
 
487
- // Returns a function, that, when invoked, will only be triggered at most once
488
- // during a given window of time.
489
- _.throttle = function(func, wait) {
490
- return limit(func, wait, false);
491
- };
492
-
493
549
  // Returns a function, that, as long as it continues to be invoked, will not
494
550
  // be triggered. The function will be called after it stops being called for
495
551
  // N milliseconds.
496
552
  _.debounce = function(func, wait) {
497
- return limit(func, wait, true);
553
+ var timeout;
554
+ return function() {
555
+ var context = this, args = arguments;
556
+ var later = function() {
557
+ timeout = null;
558
+ func.apply(context, args);
559
+ };
560
+ clearTimeout(timeout);
561
+ timeout = setTimeout(later, wait);
562
+ };
498
563
  };
499
564
 
500
565
  // Returns a function that will be executed at most one time, no matter how
@@ -513,7 +578,7 @@
513
578
  // conditionally execute the original function.
514
579
  _.wrap = function(func, wrapper) {
515
580
  return function() {
516
- var args = [func].concat(slice.call(arguments));
581
+ var args = [func].concat(slice.call(arguments, 0));
517
582
  return wrapper.apply(this, args);
518
583
  };
519
584
  };
@@ -521,9 +586,9 @@
521
586
  // Returns a function that is the composition of a list of functions, each
522
587
  // consuming the return value of the function that follows.
523
588
  _.compose = function() {
524
- var funcs = slice.call(arguments);
589
+ var funcs = arguments;
525
590
  return function() {
526
- var args = slice.call(arguments);
591
+ var args = arguments;
527
592
  for (var i = funcs.length - 1; i >= 0; i--) {
528
593
  args = [funcs[i].apply(this, args)];
529
594
  }
@@ -533,12 +598,12 @@
533
598
 
534
599
  // Returns a function that will only be executed after being called N times.
535
600
  _.after = function(times, func) {
601
+ if (times <= 0) return func();
536
602
  return function() {
537
603
  if (--times < 1) { return func.apply(this, arguments); }
538
604
  };
539
605
  };
540
606
 
541
-
542
607
  // Object Functions
543
608
  // ----------------
544
609
 
@@ -547,7 +612,7 @@
547
612
  _.keys = nativeKeys || function(obj) {
548
613
  if (obj !== Object(obj)) throw new TypeError('Invalid object');
549
614
  var keys = [];
550
- for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
615
+ for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
551
616
  return keys;
552
617
  };
553
618
 
@@ -570,7 +635,7 @@
570
635
  _.extend = function(obj) {
571
636
  each(slice.call(arguments, 1), function(source) {
572
637
  for (var prop in source) {
573
- if (source[prop] !== void 0) obj[prop] = source[prop];
638
+ obj[prop] = source[prop];
574
639
  }
575
640
  });
576
641
  return obj;
@@ -588,6 +653,7 @@
588
653
 
589
654
  // Create a (shallow-cloned) duplicate of an object.
590
655
  _.clone = function(obj) {
656
+ if (!_.isObject(obj)) return obj;
591
657
  return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
592
658
  };
593
659
 
@@ -599,50 +665,104 @@
599
665
  return obj;
600
666
  };
601
667
 
602
- // Perform a deep comparison to check if two objects are equal.
603
- _.isEqual = function(a, b) {
604
- // Check object identity.
605
- if (a === b) return true;
606
- // Different types?
607
- var atype = typeof(a), btype = typeof(b);
608
- if (atype != btype) return false;
609
- // Basic equality test (watch out for coercions).
610
- if (a == b) return true;
611
- // One is falsy and the other truthy.
612
- if ((!a && b) || (a && !b)) return false;
668
+ // Internal recursive comparison function.
669
+ function eq(a, b, stack) {
670
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
671
+ // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
672
+ if (a === b) return a !== 0 || 1 / a == 1 / b;
673
+ // A strict comparison is necessary because `null == undefined`.
674
+ if (a == null || b == null) return a === b;
613
675
  // Unwrap any wrapped objects.
614
676
  if (a._chain) a = a._wrapped;
615
677
  if (b._chain) b = b._wrapped;
616
- // One of them implements an isEqual()?
617
- if (a.isEqual) return a.isEqual(b);
618
- if (b.isEqual) return b.isEqual(a);
619
- // Check dates' integer values.
620
- if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
621
- // Both are NaN?
622
- if (_.isNaN(a) && _.isNaN(b)) return false;
623
- // Compare regular expressions.
624
- if (_.isRegExp(a) && _.isRegExp(b))
625
- return a.source === b.source &&
626
- a.global === b.global &&
627
- a.ignoreCase === b.ignoreCase &&
628
- a.multiline === b.multiline;
629
- // If a is not an object by this point, we can't handle it.
630
- if (atype !== 'object') return false;
631
- // Check for different array lengths before comparing contents.
632
- if (a.length && (a.length !== b.length)) return false;
633
- // Nothing else worked, deep compare the contents.
634
- var aKeys = _.keys(a), bKeys = _.keys(b);
635
- // Different object sizes?
636
- if (aKeys.length != bKeys.length) return false;
637
- // Recursive comparison of contents.
638
- for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
639
- return true;
678
+ // Invoke a custom `isEqual` method if one is provided.
679
+ if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
680
+ if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
681
+ // Compare `[[Class]]` names.
682
+ var className = toString.call(a);
683
+ if (className != toString.call(b)) return false;
684
+ switch (className) {
685
+ // Strings, numbers, dates, and booleans are compared by value.
686
+ case '[object String]':
687
+ // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
688
+ // equivalent to `new String("5")`.
689
+ return a == String(b);
690
+ case '[object Number]':
691
+ // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
692
+ // other numeric values.
693
+ return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
694
+ case '[object Date]':
695
+ case '[object Boolean]':
696
+ // Coerce dates and booleans to numeric primitive values. Dates are compared by their
697
+ // millisecond representations. Note that invalid dates with millisecond representations
698
+ // of `NaN` are not equivalent.
699
+ return +a == +b;
700
+ // RegExps are compared by their source patterns and flags.
701
+ case '[object RegExp]':
702
+ return a.source == b.source &&
703
+ a.global == b.global &&
704
+ a.multiline == b.multiline &&
705
+ a.ignoreCase == b.ignoreCase;
706
+ }
707
+ if (typeof a != 'object' || typeof b != 'object') return false;
708
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
709
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
710
+ var length = stack.length;
711
+ while (length--) {
712
+ // Linear search. Performance is inversely proportional to the number of
713
+ // unique nested structures.
714
+ if (stack[length] == a) return true;
715
+ }
716
+ // Add the first object to the stack of traversed objects.
717
+ stack.push(a);
718
+ var size = 0, result = true;
719
+ // Recursively compare objects and arrays.
720
+ if (className == '[object Array]') {
721
+ // Compare array lengths to determine if a deep comparison is necessary.
722
+ size = a.length;
723
+ result = size == b.length;
724
+ if (result) {
725
+ // Deep compare the contents, ignoring non-numeric properties.
726
+ while (size--) {
727
+ // Ensure commutative equality for sparse arrays.
728
+ if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
729
+ }
730
+ }
731
+ } else {
732
+ // Objects with different constructors are not equivalent.
733
+ if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
734
+ // Deep compare objects.
735
+ for (var key in a) {
736
+ if (_.has(a, key)) {
737
+ // Count the expected number of properties.
738
+ size++;
739
+ // Deep compare each member.
740
+ if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
741
+ }
742
+ }
743
+ // Ensure that both objects contain the same number of properties.
744
+ if (result) {
745
+ for (key in b) {
746
+ if (_.has(b, key) && !(size--)) break;
747
+ }
748
+ result = !size;
749
+ }
750
+ }
751
+ // Remove the first object from the stack of traversed objects.
752
+ stack.pop();
753
+ return result;
754
+ }
755
+
756
+ // Perform a deep comparison to check if two objects are equal.
757
+ _.isEqual = function(a, b) {
758
+ return eq(a, b, []);
640
759
  };
641
760
 
642
- // Is a given array or object empty?
761
+ // Is a given array, string, or object empty?
762
+ // An "empty" object has no enumerable own-properties.
643
763
  _.isEmpty = function(obj) {
644
764
  if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
645
- for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
765
+ for (var key in obj) if (_.has(obj, key)) return false;
646
766
  return true;
647
767
  };
648
768
 
@@ -654,7 +774,7 @@
654
774
  // Is a given value an array?
655
775
  // Delegates to ECMA5's native Array.isArray
656
776
  _.isArray = nativeIsArray || function(obj) {
657
- return toString.call(obj) === '[object Array]';
777
+ return toString.call(obj) == '[object Array]';
658
778
  };
659
779
 
660
780
  // Is a given variable an object?
@@ -664,43 +784,48 @@
664
784
 
665
785
  // Is a given variable an arguments object?
666
786
  _.isArguments = function(obj) {
667
- return !!(obj && hasOwnProperty.call(obj, 'callee'));
787
+ return toString.call(obj) == '[object Arguments]';
668
788
  };
789
+ if (!_.isArguments(arguments)) {
790
+ _.isArguments = function(obj) {
791
+ return !!(obj && _.has(obj, 'callee'));
792
+ };
793
+ }
669
794
 
670
795
  // Is a given value a function?
671
796
  _.isFunction = function(obj) {
672
- return !!(obj && obj.constructor && obj.call && obj.apply);
797
+ return toString.call(obj) == '[object Function]';
673
798
  };
674
799
 
675
800
  // Is a given value a string?
676
801
  _.isString = function(obj) {
677
- return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
802
+ return toString.call(obj) == '[object String]';
678
803
  };
679
804
 
680
805
  // Is a given value a number?
681
806
  _.isNumber = function(obj) {
682
- return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
807
+ return toString.call(obj) == '[object Number]';
683
808
  };
684
809
 
685
- // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
686
- // that does not equal itself.
810
+ // Is the given value `NaN`?
687
811
  _.isNaN = function(obj) {
812
+ // `NaN` is the only value for which `===` is not reflexive.
688
813
  return obj !== obj;
689
814
  };
690
815
 
691
816
  // Is a given value a boolean?
692
817
  _.isBoolean = function(obj) {
693
- return obj === true || obj === false;
818
+ return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
694
819
  };
695
820
 
696
821
  // Is a given value a date?
697
822
  _.isDate = function(obj) {
698
- return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
823
+ return toString.call(obj) == '[object Date]';
699
824
  };
700
825
 
701
826
  // Is the given value a regular expression?
702
827
  _.isRegExp = function(obj) {
703
- return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
828
+ return toString.call(obj) == '[object RegExp]';
704
829
  };
705
830
 
706
831
  // Is a given value equal to null?
@@ -713,6 +838,11 @@
713
838
  return obj === void 0;
714
839
  };
715
840
 
841
+ // Has own property?
842
+ _.has = function(obj, key) {
843
+ return hasOwnProperty.call(obj, key);
844
+ };
845
+
716
846
  // Utility Functions
717
847
  // -----------------
718
848
 
@@ -733,6 +863,11 @@
733
863
  for (var i = 0; i < n; i++) iterator.call(context, i);
734
864
  };
735
865
 
866
+ // Escape a string for HTML interpolation.
867
+ _.escape = function(string) {
868
+ return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
869
+ };
870
+
736
871
  // Add your own custom functions to the Underscore object, ensuring that
737
872
  // they're correctly added to the OOP wrapper as well.
738
873
  _.mixin = function(obj) {
@@ -753,7 +888,19 @@
753
888
  // following template settings to use alternative delimiters.
754
889
  _.templateSettings = {
755
890
  evaluate : /<%([\s\S]+?)%>/g,
756
- interpolate : /<%=([\s\S]+?)%>/g
891
+ interpolate : /<%=([\s\S]+?)%>/g,
892
+ escape : /<%-([\s\S]+?)%>/g
893
+ };
894
+
895
+ // When customizing `templateSettings`, if you don't want to define an
896
+ // interpolation, evaluation or escaping regex, we need one that is
897
+ // guaranteed not to match.
898
+ var noMatch = /.^/;
899
+
900
+ // Within an interpolation, evaluation, or escaping, remove HTML escaping
901
+ // that had been previously added.
902
+ var unescape = function(code) {
903
+ return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
757
904
  };
758
905
 
759
906
  // JavaScript micro-templating, similar to John Resig's implementation.
@@ -765,19 +912,29 @@
765
912
  'with(obj||{}){__p.push(\'' +
766
913
  str.replace(/\\/g, '\\\\')
767
914
  .replace(/'/g, "\\'")
768
- .replace(c.interpolate, function(match, code) {
769
- return "'," + code.replace(/\\'/g, "'") + ",'";
915
+ .replace(c.escape || noMatch, function(match, code) {
916
+ return "',_.escape(" + unescape(code) + "),'";
770
917
  })
771
- .replace(c.evaluate || null, function(match, code) {
772
- return "');" + code.replace(/\\'/g, "'")
773
- .replace(/[\r\n\t]/g, ' ') + "__p.push('";
918
+ .replace(c.interpolate || noMatch, function(match, code) {
919
+ return "'," + unescape(code) + ",'";
920
+ })
921
+ .replace(c.evaluate || noMatch, function(match, code) {
922
+ return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
774
923
  })
775
924
  .replace(/\r/g, '\\r')
776
925
  .replace(/\n/g, '\\n')
777
926
  .replace(/\t/g, '\\t')
778
927
  + "');}return __p.join('');";
779
- var func = new Function('obj', tmpl);
780
- return data ? func(data) : func;
928
+ var func = new Function('obj', '_', tmpl);
929
+ if (data) return func(data, _);
930
+ return function(data) {
931
+ return func.call(this, data, _);
932
+ };
933
+ };
934
+
935
+ // Add a "chain" function, which will delegate to the wrapper.
936
+ _.chain = function(obj) {
937
+ return _(obj).chain();
781
938
  };
782
939
 
783
940
  // The OOP Wrapper
@@ -812,8 +969,11 @@
812
969
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
813
970
  var method = ArrayProto[name];
814
971
  wrapper.prototype[name] = function() {
815
- method.apply(this._wrapped, arguments);
816
- return result(this._wrapped, this._chain);
972
+ var wrapped = this._wrapped;
973
+ method.apply(wrapped, arguments);
974
+ var length = wrapped.length;
975
+ if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
976
+ return result(wrapped, this._chain);
817
977
  };
818
978
  });
819
979
 
@@ -836,4 +996,4 @@
836
996
  return this._wrapped;
837
997
  };
838
998
 
839
- })();
999
+ }).call(this);