Created
October 15, 2013 13:11
-
-
Save rochapablo/6991346 to your computer and use it in GitHub Desktop.
LINQ for JavaScript
https://linqjs.codeplex.com/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// extension for jQuery | |
(function (root) { | |
if (root.Enumerable == null) { | |
throw new Error("can't find Enumerable. linq.jquery.js must load after linq.js"); | |
} | |
if (root.jQuery == null) { | |
throw new Error("can't find jQuery. linq.jquery.js must load after jQuery"); | |
} | |
var Enumerable = root.Enumerable; | |
var $ = root.jQuery; | |
$.fn.toEnumerable = function () { | |
/// <summary>each contains elements. to Enumerable<jQuery>.</summary> | |
return Enumerable.from(this).select(function (e) { return $(e) }); | |
}; | |
Enumerable.prototype.tojQuery = function () { | |
/// <summary>Enumerable to jQuery. All elements add to blank jQuery object.</summary> | |
return this.aggregate($(), function (j, x) { return j.add(x); }); | |
}; | |
Enumerable.prototype.tojQueryAsArray = function () { | |
/// <summary>Enumerable to jQuery. This behavior is $(this.toArray()).</summary> | |
return $(this.toArray()); | |
}; | |
})(this); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*-------------------------------------------------------------------------- | |
* linq.js - LINQ for JavaScript | |
* ver 3.0.4-Beta5 (Jun. 20th, 2013) | |
* | |
* created and maintained by neuecc <[email protected]> | |
* licensed under MIT License | |
* http://linqjs.codeplex.com/ | |
*------------------------------------------------------------------------*/ | |
(function(x,j){var l="enumerator is disposed",q="single:sequence contains more than one element.",a=false,b=null,e=true,g={Identity:function(a){return a},True:function(){return e},Blank:function(){}},i={Boolean:typeof e,Number:typeof 0,String:typeof"",Object:typeof{},Undefined:typeof j,Function:typeof function(){}},t={"":g.Identity},d={createLambda:function(a){if(a==b)return g.Identity;if(typeof a===i.String){var c=t[a];if(c!=b)return c;if(a.indexOf("=>")===-1){var n=new RegExp("[$]+","g"),d=0,k;while((k=n.exec(a))!=b){var f=k[0].length;if(f>d)d=f}for(var h=[],e=1;e<=d;e++){for(var j="",m=0;m<e;m++)j+="$";h.push(j)}var o=Array.prototype.join.call(h,",");c=new Function(o,"return "+a);t[a]=c;return c}else{var l=a.match(/^[(\s]*([^()]*?)[)\s]*=>(.*)/);c=new Function(l[1],"return "+l[2]);t[a]=c;return c}}return a},isIEnumerable:function(b){if(typeof Enumerator!==i.Undefined)try{new Enumerator(b);return e}catch(c){}return a},defineProperty:Object.defineProperties!=b?function(c,b,d){Object.defineProperty(c,b,{enumerable:a,configurable:e,writable:e,value:d})}:function(b,a,c){b[a]=c},compare:function(a,b){return a===b?0:a>b?1:-1},dispose:function(a){a!=b&&a.dispose()}},o={Before:0,Running:1,After:2},f=function(d,f,g){var c=new v,b=o.Before;this.current=c.current;this.moveNext=function(){try{switch(b){case o.Before:b=o.Running;d();case o.Running:if(f.apply(c))return e;else{this.dispose();return a}case o.After:return a}}catch(g){this.dispose();throw g;}};this.dispose=function(){if(b!=o.Running)return;try{g()}finally{b=o.After}}},v=function(){var c=b;this.current=function(){return c};this.yieldReturn=function(a){c=a;return e};this.yieldBreak=function(){return a}},c=function(a){this.getEnumerator=a};c.Utils={};c.Utils.createLambda=function(a){return d.createLambda(a)};c.Utils.createEnumerable=function(a){return new c(a)};c.Utils.createEnumerator=function(a,b,c){return new f(a,b,c)};c.Utils.extendTo=function(i){var e=i.prototype,f;if(i===Array){f=h.prototype;d.defineProperty(e,"getSource",function(){return this})}else{f=c.prototype;d.defineProperty(e,"getEnumerator",function(){return c.from(this).getEnumerator()})}for(var a in f){var g=f[a];if(e[a]==g)continue;if(e[a]!=b){a=a+"ByLinq";if(e[a]==g)continue}g instanceof Function&&d.defineProperty(e,a,g)}};c.choice=function(){var a=arguments;return new c(function(){return new f(function(){a=a[0]instanceof Array?a[0]:a[0].getEnumerator!=b?a[0].toArray():a},function(){return this.yieldReturn(a[Math.floor(Math.random()*a.length)])},g.Blank)})};c.cycle=function(){var a=arguments;return new c(function(){var c=0;return new f(function(){a=a[0]instanceof Array?a[0]:a[0].getEnumerator!=b?a[0].toArray():a},function(){if(c>=a.length)c=0;return this.yieldReturn(a[c++])},g.Blank)})};c.empty=function(){return new c(function(){return new f(g.Blank,function(){return a},g.Blank)})};c.from=function(j){if(j==b)return c.empty();if(j instanceof c)return j;if(typeof j==i.Number||typeof j==i.Boolean)return c.repeat(j,1);if(typeof j==i.String)return new c(function(){var b=0;return new f(g.Blank,function(){return b<j.length?this.yieldReturn(j.charAt(b++)):a},g.Blank)});if(typeof j!=i.Function){if(typeof j.length==i.Number)return new h(j);if(!(j instanceof Object)&&d.isIEnumerable(j))return new c(function(){var c=e,b;return new f(function(){b=new Enumerator(j)},function(){if(c)c=a;else b.moveNext();return b.atEnd()?a:this.yieldReturn(b.item())},g.Blank)});if(typeof Windows===i.Object&&typeof j.first===i.Function)return new c(function(){var c=e,b;return new f(function(){b=j.first()},function(){if(c)c=a;else b.moveNext();return b.hasCurrent?this.yieldReturn(b.current):this.yieldBreak()},g.Blank)})}return new c(function(){var b=[],c=0;return new f(function(){for(var a in j){var c=j[a];!(c instanceof Function)&&Object.prototype.hasOwnProperty.call(j,a)&&b.push({key:a,value:c})}},function(){return c<b.length?this.yieldReturn(b[c++]):a},g.Blank)})},c.make=function(a){return c.repeat(a,1)};c.matches=function(h,e,d){if(d==b)d="";if(e instanceof RegExp){d+=e.ignoreCase?"i":"";d+=e.multiline?"m":"";e=e.source}if(d.indexOf("g")===-1)d+="g";return new c(function(){var b;return new f(function(){b=new RegExp(e,d)},function(){var c=b.exec(h);return c?this.yieldReturn(c):a},g.Blank)})};c.range=function(e,d,a){if(a==b)a=1;return new c(function(){var b,c=0;return new f(function(){b=e-a},function(){return c++<d?this.yieldReturn(b+=a):this.yieldBreak()},g.Blank)})};c.rangeDown=function(e,d,a){if(a==b)a=1;return new c(function(){var b,c=0;return new f(function(){b=e+a},function(){return c++<d?this.yieldReturn(b-=a):this.yieldBreak()},g.Blank)})};c.rangeTo=function(d,e,a){if(a==b)a=1;return d<e?new c(function(){var b;return new f(function(){b=d-a},function(){var c=b+=a;return c<=e?this.yieldReturn(c):this.yieldBreak()},g.Blank)}):new c(function(){var b;return new f(function(){b=d+a},function(){var c=b-=a;return c>=e?this.yieldReturn(c):this.yieldBreak()},g.Blank)})};c.repeat=function(a,d){return d!=b?c.repeat(a).take(d):new c(function(){return new f(g.Blank,function(){return this.yieldReturn(a)},g.Blank)})};c.repeatWithFinalize=function(a,e){a=d.createLambda(a);e=d.createLambda(e);return new c(function(){var c;return new f(function(){c=a()},function(){return this.yieldReturn(c)},function(){if(c!=b){e(c);c=b}})})};c.generate=function(a,e){if(e!=b)return c.generate(a).take(e);a=d.createLambda(a);return new c(function(){return new f(g.Blank,function(){return this.yieldReturn(a())},g.Blank)})};c.toInfinity=function(d,a){if(d==b)d=0;if(a==b)a=1;return new c(function(){var b;return new f(function(){b=d-a},function(){return this.yieldReturn(b+=a)},g.Blank)})};c.toNegativeInfinity=function(d,a){if(d==b)d=0;if(a==b)a=1;return new c(function(){var b;return new f(function(){b=d+a},function(){return this.yieldReturn(b-=a)},g.Blank)})};c.unfold=function(h,b){b=d.createLambda(b);return new c(function(){var d=e,c;return new f(g.Blank,function(){if(d){d=a;c=h;return this.yieldReturn(c)}c=b(c);return this.yieldReturn(c)},g.Blank)})};c.defer=function(a){return new c(function(){var b;return new f(function(){b=c.from(a()).getEnumerator()},function(){return b.moveNext()?this.yieldReturn(b.current()):this.yieldBreak()},function(){d.dispose(b)})})};c.prototype.traverseBreadthFirst=function(g,b){var h=this;g=d.createLambda(g);b=d.createLambda(b);return new c(function(){var i,k=0,j=[];return new f(function(){i=h.getEnumerator()},function(){while(e){if(i.moveNext()){j.push(i.current());return this.yieldReturn(b(i.current(),k))}var f=c.from(j).selectMany(function(a){return g(a)});if(!f.any())return a;else{k++;j=[];d.dispose(i);i=f.getEnumerator()}}},function(){d.dispose(i)})})};c.prototype.traverseDepthFirst=function(g,b){var h=this;g=d.createLambda(g);b=d.createLambda(b);return new c(function(){var j=[],i;return new f(function(){i=h.getEnumerator()},function(){while(e){if(i.moveNext()){var f=b(i.current(),j.length);j.push(i);i=c.from(g(i.current())).getEnumerator();return this.yieldReturn(f)}if(j.length<=0)return a;d.dispose(i);i=j.pop()}},function(){try{d.dispose(i)}finally{c.from(j).forEach(function(a){a.dispose()})}})})};c.prototype.flatten=function(){var h=this;return new c(function(){var j,i=b;return new f(function(){j=h.getEnumerator()},function(){while(e){if(i!=b)if(i.moveNext())return this.yieldReturn(i.current());else i=b;if(j.moveNext())if(j.current()instanceof Array){d.dispose(i);i=c.from(j.current()).selectMany(g.Identity).flatten().getEnumerator();continue}else return this.yieldReturn(j.current());return a}},function(){try{d.dispose(j)}finally{d.dispose(i)}})})};c.prototype.pairwise=function(b){var e=this;b=d.createLambda(b);return new c(function(){var c;return new f(function(){c=e.getEnumerator();c.moveNext()},function(){var d=c.current();return c.moveNext()?this.yieldReturn(b(d,c.current())):a},function(){d.dispose(c)})})};c.prototype.scan=function(i,g){var h;if(g==b){g=d.createLambda(i);h=a}else{g=d.createLambda(g);h=e}var j=this;return new c(function(){var b,c,k=e;return new f(function(){b=j.getEnumerator()},function(){if(k){k=a;if(!h){if(b.moveNext())return this.yieldReturn(c=b.current())}else return this.yieldReturn(c=i)}return b.moveNext()?this.yieldReturn(c=g(c,b.current())):a},function(){d.dispose(b)})})};c.prototype.select=function(e){e=d.createLambda(e);if(e.length<=1)return new m(this,b,e);else{var g=this;return new c(function(){var b,c=0;return new f(function(){b=g.getEnumerator()},function(){return b.moveNext()?this.yieldReturn(e(b.current(),c++)):a},function(){d.dispose(b)})})}};c.prototype.selectMany=function(g,e){var h=this;g=d.createLambda(g);if(e==b)e=function(b,a){return a};e=d.createLambda(e);return new c(function(){var k,i=j,l=0;return new f(function(){k=h.getEnumerator()},function(){if(i===j)if(!k.moveNext())return a;do{if(i==b){var f=g(k.current(),l++);i=c.from(f).getEnumerator()}if(i.moveNext())return this.yieldReturn(e(k.current(),i.current()));d.dispose(i);i=b}while(k.moveNext());return a},function(){try{d.dispose(k)}finally{d.dispose(i)}})})};c.prototype.where=function(b){b=d.createLambda(b);if(b.length<=1)return new n(this,b);else{var e=this;return new c(function(){var c,g=0;return new f(function(){c=e.getEnumerator()},function(){while(c.moveNext())if(b(c.current(),g++))return this.yieldReturn(c.current());return a},function(){d.dispose(c)})})}};c.prototype.choose=function(a){a=d.createLambda(a);var e=this;return new c(function(){var c,g=0;return new f(function(){c=e.getEnumerator()},function(){while(c.moveNext()){var d=a(c.current(),g++);if(d!=b)return this.yieldReturn(d)}return this.yieldBreak()},function(){d.dispose(c)})})};c.prototype.ofType=function(c){var a;switch(c){case Number:a=i.Number;break;case String:a=i.String;break;case Boolean:a=i.Boolean;break;case Function:a=i.Function;break;default:a=b}return a===b?this.where(function(a){return a instanceof c}):this.where(function(b){return typeof b===a})};c.prototype.zip=function(){var i=arguments,e=d.createLambda(arguments[arguments.length-1]),g=this;if(arguments.length==2){var h=arguments[0];return new c(function(){var i,b,j=0;return new f(function(){i=g.getEnumerator();b=c.from(h).getEnumerator()},function(){return i.moveNext()&&b.moveNext()?this.yieldReturn(e(i.current(),b.current(),j++)):a},function(){try{d.dispose(i)}finally{d.dispose(b)}})})}else return new c(function(){var a,h=0;return new f(function(){var b=c.make(g).concat(c.from(i).takeExceptLast().select(c.from)).select(function(a){return a.getEnumerator()}).toArray();a=c.from(b)},function(){if(a.all(function(a){return a.moveNext()})){var c=a.select(function(a){return a.current()}).toArray();c.push(h++);return this.yieldReturn(e.apply(b,c))}else return this.yieldBreak()},function(){c.from(a).forEach(d.dispose)})})};c.prototype.merge=function(){var b=arguments,a=this;return new c(function(){var e,g=-1;return new f(function(){e=c.make(a).concat(c.from(b).select(c.from)).select(function(a){return a.getEnumerator()}).toArray()},function(){while(e.length>0){g=g>=e.length-1?0:g+1;var a=e[g];if(a.moveNext())return this.yieldReturn(a.current());else{a.dispose();e.splice(g--,1)}}return this.yieldBreak()},function(){c.from(e).forEach(d.dispose)})})};c.prototype.join=function(n,i,h,l,k){i=d.createLambda(i);h=d.createLambda(h);l=d.createLambda(l);k=d.createLambda(k);var m=this;return new c(function(){var o,r,p=b,q=0;return new f(function(){o=m.getEnumerator();r=c.from(n).toLookup(h,g.Identity,k)},function(){while(e){if(p!=b){var c=p[q++];if(c!==j)return this.yieldReturn(l(o.current(),c));c=b;q=0}if(o.moveNext()){var d=i(o.current());p=r.get(d).toArray()}else return a}},function(){d.dispose(o)})})};c.prototype.groupJoin=function(l,h,e,j,i){h=d.createLambda(h);e=d.createLambda(e);j=d.createLambda(j);i=d.createLambda(i);var k=this;return new c(function(){var m=k.getEnumerator(),n=b;return new f(function(){m=k.getEnumerator();n=c.from(l).toLookup(e,g.Identity,i)},function(){if(m.moveNext()){var b=n.get(h(m.current()));return this.yieldReturn(j(m.current(),b))}return a},function(){d.dispose(m)})})};c.prototype.all=function(b){b=d.createLambda(b);var c=e;this.forEach(function(d){if(!b(d)){c=a;return a}});return c};c.prototype.any=function(c){c=d.createLambda(c);var b=this.getEnumerator();try{if(arguments.length==0)return b.moveNext();while(b.moveNext())if(c(b.current()))return e;return a}finally{d.dispose(b)}};c.prototype.isEmpty=function(){return!this.any()};c.prototype.concat=function(){var e=this;if(arguments.length==1){var g=arguments[0];return new c(function(){var i,h;return new f(function(){i=e.getEnumerator()},function(){if(h==b){if(i.moveNext())return this.yieldReturn(i.current());h=c.from(g).getEnumerator()}return h.moveNext()?this.yieldReturn(h.current()):a},function(){try{d.dispose(i)}finally{d.dispose(h)}})})}else{var h=arguments;return new c(function(){var a;return new f(function(){a=c.make(e).concat(c.from(h).select(c.from)).select(function(a){return a.getEnumerator()}).toArray()},function(){while(a.length>0){var b=a[0];if(b.moveNext())return this.yieldReturn(b.current());else{b.dispose();a.splice(0,1)}}return this.yieldBreak()},function(){c.from(a).forEach(d.dispose)})})}};c.prototype.insert=function(h,b){var g=this;return new c(function(){var j,i,l=0,k=a;return new f(function(){j=g.getEnumerator();i=c.from(b).getEnumerator()},function(){if(l==h&&i.moveNext()){k=e;return this.yieldReturn(i.current())}if(j.moveNext()){l++;return this.yieldReturn(j.current())}return!k&&i.moveNext()?this.yieldReturn(i.current()):a},function(){try{d.dispose(j)}finally{d.dispose(i)}})})};c.prototype.alternate=function(a){var g=this;return new c(function(){var j,i,k,h;return new f(function(){if(a instanceof Array||a.getEnumerator!=b)k=c.from(c.from(a).toArray());else k=c.make(a);i=g.getEnumerator();if(i.moveNext())j=i.current()},function(){while(e){if(h!=b)if(h.moveNext())return this.yieldReturn(h.current());else h=b;if(j==b&&i.moveNext()){j=i.current();h=k.getEnumerator();continue}else if(j!=b){var a=j;j=b;return this.yieldReturn(a)}return this.yieldBreak()}},function(){try{d.dispose(i)}finally{d.dispose(h)}})})};c.prototype.contains=function(f,b){b=d.createLambda(b);var c=this.getEnumerator();try{while(c.moveNext())if(b(c.current())===f)return e;return a}finally{d.dispose(c)}};c.prototype.defaultIfEmpty=function(g){var h=this;if(g===j)g=b;return new c(function(){var b,c=e;return new f(function(){b=h.getEnumerator()},function(){if(b.moveNext()){c=a;return this.yieldReturn(b.current())}else if(c){c=a;return this.yieldReturn(g)}return a},function(){d.dispose(b)})})};c.prototype.distinct=function(a){return this.except(c.empty(),a)};c.prototype.distinctUntilChanged=function(b){b=d.createLambda(b);var e=this;return new c(function(){var c,g,h;return new f(function(){c=e.getEnumerator()},function(){while(c.moveNext()){var d=b(c.current());if(h){h=a;g=d;return this.yieldReturn(c.current())}if(g===d)continue;g=d;return this.yieldReturn(c.current())}return this.yieldBreak()},function(){d.dispose(c)})})};c.prototype.except=function(e,b){b=d.createLambda(b);var g=this;return new c(function(){var h,i;return new f(function(){h=g.getEnumerator();i=new r(b);c.from(e).forEach(function(a){i.add(a)})},function(){while(h.moveNext()){var b=h.current();if(!i.contains(b)){i.add(b);return this.yieldReturn(b)}}return a},function(){d.dispose(h)})})};c.prototype.intersect=function(e,b){b=d.createLambda(b);var g=this;return new c(function(){var h,i,j;return new f(function(){h=g.getEnumerator();i=new r(b);c.from(e).forEach(function(a){i.add(a)});j=new r(b)},function(){while(h.moveNext()){var b=h.current();if(!j.contains(b)&&i.contains(b)){j.add(b);return this.yieldReturn(b)}}return a},function(){d.dispose(h)})})};c.prototype.sequenceEqual=function(h,f){f=d.createLambda(f);var g=this.getEnumerator();try{var b=c.from(h).getEnumerator();try{while(g.moveNext())if(!b.moveNext()||f(g.current())!==f(b.current()))return a;return b.moveNext()?a:e}finally{d.dispose(b)}}finally{d.dispose(g)}};c.prototype.union=function(e,b){b=d.createLambda(b);var g=this;return new c(function(){var k,h,i;return new f(function(){k=g.getEnumerator();i=new r(b)},function(){var b;if(h===j){while(k.moveNext()){b=k.current();if(!i.contains(b)){i.add(b);return this.yieldReturn(b)}}h=c.from(e).getEnumerator()}while(h.moveNext()){b=h.current();if(!i.contains(b)){i.add(b);return this.yieldReturn(b)}}return a},function(){try{d.dispose(k)}finally{d.dispose(h)}})})};c.prototype.orderBy=function(b){return new k(this,b,a)};c.prototype.orderByDescending=function(a){return new k(this,a,e)};c.prototype.reverse=function(){var b=this;return new c(function(){var c,d;return new f(function(){c=b.toArray();d=c.length},function(){return d>0?this.yieldReturn(c[--d]):a},g.Blank)})};c.prototype.shuffle=function(){var b=this;return new c(function(){var c;return new f(function(){c=b.toArray()},function(){if(c.length>0){var b=Math.floor(Math.random()*c.length);return this.yieldReturn(c.splice(b,1)[0])}return a},g.Blank)})};c.prototype.weightedSample=function(a){a=d.createLambda(a);var e=this;return new c(function(){var c,d=0;return new f(function(){c=e.choose(function(e){var c=a(e);if(c<=0)return b;d+=c;return{value:e,bound:d}}).toArray()},function(){if(c.length>0){var f=Math.floor(Math.random()*d)+1,e=-1,a=c.length;while(a-e>1){var b=Math.floor((e+a)/2);if(c[b].bound>=f)a=b;else e=b}return this.yieldReturn(c[a].value)}return this.yieldBreak()},g.Blank)})};c.prototype.groupBy=function(i,h,e,g){var j=this;i=d.createLambda(i);h=d.createLambda(h);if(e!=b)e=d.createLambda(e);g=d.createLambda(g);return new c(function(){var c;return new f(function(){c=j.toLookup(i,h,g).toEnumerable().getEnumerator()},function(){while(c.moveNext())return e==b?this.yieldReturn(c.current()):this.yieldReturn(e(c.current().key(),c.current()));return a},function(){d.dispose(c)})})};c.prototype.partitionBy=function(j,i,g,h){var l=this;j=d.createLambda(j);i=d.createLambda(i);h=d.createLambda(h);var k;if(g==b){k=a;g=function(b,a){return new u(b,a)}}else{k=e;g=d.createLambda(g)}return new c(function(){var b,n,o,m=[];return new f(function(){b=l.getEnumerator();if(b.moveNext()){n=j(b.current());o=h(n);m.push(i(b.current()))}},function(){var d;while((d=b.moveNext())==e)if(o===h(j(b.current())))m.push(i(b.current()));else break;if(m.length>0){var f=k?g(n,c.from(m)):g(n,m);if(d){n=j(b.current());o=h(n);m=[i(b.current())]}else m=[];return this.yieldReturn(f)}return a},function(){d.dispose(b)})})};c.prototype.buffer=function(e){var b=this;return new c(function(){var c;return new f(function(){c=b.getEnumerator()},function(){var b=[],d=0;while(c.moveNext()){b.push(c.current());if(++d>=e)return this.yieldReturn(b)}return b.length>0?this.yieldReturn(b):a},function(){d.dispose(c)})})};c.prototype.aggregate=function(c,b,a){a=d.createLambda(a);return a(this.scan(c,b,a).last())};c.prototype.average=function(a){a=d.createLambda(a);var c=0,b=0;this.forEach(function(d){c+=a(d);++b});return c/b};c.prototype.count=function(a){a=a==b?g.True:d.createLambda(a);var c=0;this.forEach(function(d,b){if(a(d,b))++c});return c};c.prototype.max=function(a){if(a==b)a=g.Identity;return this.select(a).aggregate(function(a,b){return a>b?a:b})};c.prototype.min=function(a){if(a==b)a=g.Identity;return this.select(a).aggregate(function(a,b){return a<b?a:b})};c.prototype.maxBy=function(a){a=d.createLambda(a);return this.aggregate(function(b,c){return a(b)>a(c)?b:c})};c.prototype.minBy=function(a){a=d.createLambda(a);return this.aggregate(function(b,c){return a(b)<a(c)?b:c})};c.prototype.sum=function(a){if(a==b)a=g.Identity;return this.select(a).aggregate(0,function(a,b){return a+b})};c.prototype.elementAt=function(d){var c,b=a;this.forEach(function(g,f){if(f==d){c=g;b=e;return a}});if(!b)throw new Error("index is less than 0 or greater than or equal to the number of elements in source.");return c};c.prototype.elementAtOrDefault=function(g,c){if(c===j)c=b;var f,d=a;this.forEach(function(c,b){if(b==g){f=c;d=e;return a}});return!d?c:f};c.prototype.first=function(c){if(c!=b)return this.where(c).first();var f,d=a;this.forEach(function(b){f=b;d=e;return a});if(!d)throw new Error("first:No element satisfies the condition.");return f};c.prototype.firstOrDefault=function(d,c){if(c===j)c=b;if(d!=b)return this.where(d).firstOrDefault(b,c);var g,f=a;this.forEach(function(b){g=b;f=e;return a});return!f?c:g};c.prototype.last=function(c){if(c!=b)return this.where(c).last();var f,d=a;this.forEach(function(a){d=e;f=a});if(!d)throw new Error("last:No element satisfies the condition.");return f};c.prototype.lastOrDefault=function(d,c){if(c===j)c=b;if(d!=b)return this.where(d).lastOrDefault(b,c);var g,f=a;this.forEach(function(a){f=e;g=a});return!f?c:g};c.prototype.single=function(d){if(d!=b)return this.where(d).single();var f,c=a;this.forEach(function(a){if(!c){c=e;f=a}else throw new Error(q);});if(!c)throw new Error("single:No element satisfies the condition.");return f};c.prototype.singleOrDefault=function(f,c){if(c===j)c=b;if(f!=b)return this.where(f).singleOrDefault(b,c);var g,d=a;this.forEach(function(a){if(!d){d=e;g=a}else throw new Error(q);});return!d?c:g};c.prototype.skip=function(e){var b=this;return new c(function(){var c,g=0;return new f(function(){c=b.getEnumerator();while(g++<e&&c.moveNext());},function(){return c.moveNext()?this.yieldReturn(c.current()):a},function(){d.dispose(c)})})};c.prototype.skipWhile=function(b){b=d.createLambda(b);var g=this;return new c(function(){var c,i=0,h=a;return new f(function(){c=g.getEnumerator()},function(){while(!h)if(c.moveNext()){if(!b(c.current(),i++)){h=e;return this.yieldReturn(c.current())}continue}else return a;return c.moveNext()?this.yieldReturn(c.current()):a},function(){d.dispose(c)})})};c.prototype.take=function(e){var b=this;return new c(function(){var c,g=0;return new f(function(){c=b.getEnumerator()},function(){return g++<e&&c.moveNext()?this.yieldReturn(c.current()):a},function(){d.dispose(c)})})};c.prototype.takeWhile=function(b){b=d.createLambda(b);var e=this;return new c(function(){var c,g=0;return new f(function(){c=e.getEnumerator()},function(){return c.moveNext()&&b(c.current(),g++)?this.yieldReturn(c.current()):a},function(){d.dispose(c)})})};c.prototype.takeExceptLast=function(e){if(e==b)e=1;var g=this;return new c(function(){if(e<=0)return g.getEnumerator();var b,c=[];return new f(function(){b=g.getEnumerator()},function(){while(b.moveNext()){if(c.length==e){c.push(b.current());return this.yieldReturn(c.shift())}c.push(b.current())}return a},function(){d.dispose(b)})})};c.prototype.takeFromLast=function(e){if(e<=0||e==b)return c.empty();var g=this;return new c(function(){var j,h,i=[];return new f(function(){j=g.getEnumerator()},function(){while(j.moveNext()){i.length==e&&i.shift();i.push(j.current())}if(h==b)h=c.from(i).getEnumerator();return h.moveNext()?this.yieldReturn(h.current()):a},function(){d.dispose(h)})})};c.prototype.indexOf=function(d){var c=b;if(typeof d===i.Function)this.forEach(function(e,b){if(d(e,b)){c=b;return a}});else this.forEach(function(e,b){if(e===d){c=b;return a}});return c!==b?c:-1};c.prototype.lastIndexOf=function(b){var a=-1;if(typeof b===i.Function)this.forEach(function(d,c){if(b(d,c))a=c});else this.forEach(function(d,c){if(d===b)a=c});return a};c.prototype.cast=function(){return this};c.prototype.asEnumerable=function(){return c.from(this)};c.prototype.toArray=function(){var a=[];this.forEach(function(b){a.push(b)});return a};c.prototype.toLookup=function(c,b,a){c=d.createLambda(c);b=d.createLambda(b);a=d.createLambda(a);var e=new r(a);this.forEach(function(g){var f=c(g),a=b(g),d=e.get(f);if(d!==j)d.push(a);else e.add(f,[a])});return new w(e)};c.prototype.toObject=function(b,a){b=d.createLambda(b);a=d.createLambda(a);var c={};this.forEach(function(d){c[b(d)]=a(d)});return c};c.prototype.toDictionary=function(c,b,a){c=d.createLambda(c);b=d.createLambda(b);a=d.createLambda(a);var e=new r(a);this.forEach(function(a){e.add(c(a),b(a))});return e};c.prototype.toJSONString=function(a,c){if(typeof JSON===i.Undefined||JSON.stringify==b)throw new Error("toJSONString can't find JSON.stringify. This works native JSON support Browser or include json2.js");return JSON.stringify(this.toArray(),a,c)};c.prototype.toJoinedString=function(a,c){if(a==b)a="";if(c==b)c=g.Identity;return this.select(c).toArray().join(a)};c.prototype.doAction=function(b){var e=this;b=d.createLambda(b);return new c(function(){var c,g=0;return new f(function(){c=e.getEnumerator()},function(){if(c.moveNext()){b(c.current(),g++);return this.yieldReturn(c.current())}return a},function(){d.dispose(c)})})};c.prototype.forEach=function(c){c=d.createLambda(c);var e=0,b=this.getEnumerator();try{while(b.moveNext())if(c(b.current(),e++)===a)break}finally{d.dispose(b)}};c.prototype.write=function(c,f){if(c==b)c="";f=d.createLambda(f);var g=e;this.forEach(function(b){if(g)g=a;else document.write(c);document.write(f(b))})};c.prototype.writeLine=function(a){a=d.createLambda(a);this.forEach(function(b){document.writeln(a(b)+"<br />")})};c.prototype.force=function(){var a=this.getEnumerator();try{while(a.moveNext());}finally{d.dispose(a)}};c.prototype.letBind=function(b){b=d.createLambda(b);var e=this;return new c(function(){var g;return new f(function(){g=c.from(b(e)).getEnumerator()},function(){return g.moveNext()?this.yieldReturn(g.current()):a},function(){d.dispose(g)})})};c.prototype.share=function(){var i=this,c,h=a;return new s(function(){return new f(function(){if(c==b)c=i.getEnumerator()},function(){if(h)throw new Error(l);return c.moveNext()?this.yieldReturn(c.current()):a},g.Blank)},function(){h=e;d.dispose(c)})};c.prototype.memoize=function(){var j=this,h,c,i=a;return new s(function(){var d=-1;return new f(function(){if(c==b){c=j.getEnumerator();h=[]}},function(){if(i)throw new Error(l);d++;return h.length<=d?c.moveNext()?this.yieldReturn(h[d]=c.current()):a:this.yieldReturn(h[d])},g.Blank)},function(){i=e;d.dispose(c);h=b})};c.prototype.catchError=function(b){b=d.createLambda(b);var e=this;return new c(function(){var c;return new f(function(){c=e.getEnumerator()},function(){try{return c.moveNext()?this.yieldReturn(c.current()):a}catch(d){b(d);return a}},function(){d.dispose(c)})})};c.prototype.finallyAction=function(b){b=d.createLambda(b);var e=this;return new c(function(){var c;return new f(function(){c=e.getEnumerator()},function(){return c.moveNext()?this.yieldReturn(c.current()):a},function(){try{d.dispose(c)}finally{b()}})})};c.prototype.log=function(a){a=d.createLambda(a);return this.doAction(function(b){typeof console!==i.Undefined&&console.log(a(b))})};c.prototype.trace=function(c,a){if(c==b)c="Trace";a=d.createLambda(a);return this.doAction(function(b){typeof console!==i.Undefined&&console.log(c,a(b))})};var k=function(f,b,c,e){var a=this;a.source=f;a.keySelector=d.createLambda(b);a.descending=c;a.parent=e};k.prototype=new c;k.prototype.createOrderedEnumerable=function(a,b){return new k(this.source,a,b,this)};k.prototype.thenBy=function(b){return this.createOrderedEnumerable(b,a)};k.prototype.thenByDescending=function(a){return this.createOrderedEnumerable(a,e)};k.prototype.getEnumerator=function(){var h=this,d,c,e=0;return new f(function(){d=[];c=[];h.source.forEach(function(b,a){d.push(b);c.push(a)});var a=p.create(h,b);a.GenerateKeys(d);c.sort(function(b,c){return a.compare(b,c)})},function(){return e<c.length?this.yieldReturn(d[c[e++]]):a},g.Blank)};var p=function(c,d,e){var a=this;a.keySelector=c;a.descending=d;a.child=e;a.keys=b};p.create=function(a,d){var c=new p(a.keySelector,a.descending,d);return a.parent!=b?p.create(a.parent,c):c};p.prototype.GenerateKeys=function(d){var a=this;for(var f=d.length,g=a.keySelector,e=new Array(f),c=0;c<f;c++)e[c]=g(d[c]);a.keys=e;a.child!=b&&a.child.GenerateKeys(d)};p.prototype.compare=function(e,f){var a=this,c=d.compare(a.keys[e],a.keys[f]);return c==0?a.child!=b?a.child.compare(e,f):d.compare(e,f):a.descending?-c:c};var s=function(a,b){this.dispose=b;c.call(this,a)};s.prototype=new c;var h=function(a){this.getSource=function(){return a}};h.prototype=new c;h.prototype.any=function(a){return a==b?this.getSource().length>0:c.prototype.any.apply(this,arguments)};h.prototype.count=function(a){return a==b?this.getSource().length:c.prototype.count.apply(this,arguments)};h.prototype.elementAt=function(a){var b=this.getSource();return 0<=a&&a<b.length?b[a]:c.prototype.elementAt.apply(this,arguments)};h.prototype.elementAtOrDefault=function(c,a){if(a===j)a=b;var d=this.getSource();return 0<=c&&c<d.length?d[c]:a};h.prototype.first=function(d){var a=this.getSource();return d==b&&a.length>0?a[0]:c.prototype.first.apply(this,arguments)};h.prototype.firstOrDefault=function(e,a){if(a===j)a=b;if(e!=b)return c.prototype.firstOrDefault.apply(this,arguments);var d=this.getSource();return d.length>0?d[0]:a};h.prototype.last=function(d){var a=this.getSource();return d==b&&a.length>0?a[a.length-1]:c.prototype.last.apply(this,arguments)};h.prototype.lastOrDefault=function(e,a){if(a===j)a=b;if(e!=b)return c.prototype.lastOrDefault.apply(this,arguments);var d=this.getSource();return d.length>0?d[d.length-1]:a};h.prototype.skip=function(d){var b=this.getSource();return new c(function(){var c;return new f(function(){c=d<0?0:d},function(){return c<b.length?this.yieldReturn(b[c++]):a},g.Blank)})};h.prototype.takeExceptLast=function(a){if(a==b)a=1;return this.take(this.getSource().length-a)};h.prototype.takeFromLast=function(a){return this.skip(this.getSource().length-a)};h.prototype.reverse=function(){var b=this.getSource();return new c(function(){var c;return new f(function(){c=b.length},function(){return c>0?this.yieldReturn(b[--c]):a},g.Blank)})};h.prototype.sequenceEqual=function(d,e){return(d instanceof h||d instanceof Array)&&e==b&&c.from(d).count()!=this.count()?a:c.prototype.sequenceEqual.apply(this,arguments)};h.prototype.toJoinedString=function(a,e){var d=this.getSource();if(e!=b||!(d instanceof Array))return c.prototype.toJoinedString.apply(this,arguments);if(a==b)a="";return d.join(a)};h.prototype.getEnumerator=function(){var a=this.getSource(),b=-1;return{current:function(){return a[b]},moveNext:function(){return++b<a.length},dispose:g.Blank}};var n=function(b,a){this.prevSource=b;this.prevPredicate=a};n.prototype=new c;n.prototype.where=function(a){a=d.createLambda(a);if(a.length<=1){var e=this.prevPredicate,b=function(b){return e(b)&&a(b)};return new n(this.prevSource,b)}else return c.prototype.where.call(this,a)};n.prototype.select=function(a){a=d.createLambda(a);return a.length<=1?new m(this.prevSource,this.prevPredicate,a):c.prototype.select.call(this,a)};n.prototype.getEnumerator=function(){var c=this.prevPredicate,e=this.prevSource,b;return new f(function(){b=e.getEnumerator()},function(){while(b.moveNext())if(c(b.current()))return this.yieldReturn(b.current());return a},function(){d.dispose(b)})};var m=function(c,a,b){this.prevSource=c;this.prevPredicate=a;this.prevSelector=b};m.prototype=new c;m.prototype.where=function(a){a=d.createLambda(a);return a.length<=1?new n(this,a):c.prototype.where.call(this,a)};m.prototype.select=function(a){var b=this;a=d.createLambda(a);if(a.length<=1){var f=b.prevSelector,e=function(b){return a(f(b))};return new m(b.prevSource,b.prevPredicate,e)}else return c.prototype.select.call(b,a)};m.prototype.getEnumerator=function(){var e=this.prevPredicate,g=this.prevSelector,h=this.prevSource,c;return new f(function(){c=h.getEnumerator()},function(){while(c.moveNext())if(e==b||e(c.current()))return this.yieldReturn(g(c.current()));return a},function(){d.dispose(c)})};var r=function(){var d=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)},h=function(a){return a===b?"null":a===j?"undefined":typeof a.toString===i.Function?a.toString():Object.prototype.toString.call(a)},m=function(d,c){var a=this;a.key=d;a.value=c;a.prev=b;a.next=b},k=function(){this.first=b;this.last=b};k.prototype={addLast:function(c){var a=this;if(a.last!=b){a.last.next=c;c.prev=a.last;a.last=c}else a.first=a.last=c},replace:function(c,a){if(c.prev!=b){c.prev.next=a;a.prev=c.prev}else this.first=a;if(c.next!=b){c.next.prev=a;a.next=c.next}else this.last=a},remove:function(a){if(a.prev!=b)a.prev.next=a.next;else this.first=a.next;if(a.next!=b)a.next.prev=a.prev;else this.last=a.prev}};var l=function(c){var a=this;a.countField=0;a.entryList=new k;a.buckets={};a.compareSelector=c==b?g.Identity:c};l.prototype={add:function(i,j){var a=this,g=a.compareSelector(i),f=h(g),c=new m(i,j);if(d(a.buckets,f)){for(var b=a.buckets[f],e=0;e<b.length;e++)if(a.compareSelector(b[e].key)===g){a.entryList.replace(b[e],c);b[e]=c;return}b.push(c)}else a.buckets[f]=[c];a.countField++;a.entryList.addLast(c)},"get":function(i){var a=this,c=a.compareSelector(i),g=h(c);if(!d(a.buckets,g))return j;for(var e=a.buckets[g],b=0;b<e.length;b++){var f=e[b];if(a.compareSelector(f.key)===c)return f.value}return j},"set":function(k,l){var b=this,g=b.compareSelector(k),j=h(g);if(d(b.buckets,j))for(var f=b.buckets[j],c=0;c<f.length;c++)if(b.compareSelector(f[c].key)===g){var i=new m(k,l);b.entryList.replace(f[c],i);f[c]=i;return e}return a},contains:function(j){var b=this,f=b.compareSelector(j),i=h(f);if(!d(b.buckets,i))return a;for(var g=b.buckets[i],c=0;c<g.length;c++)if(b.compareSelector(g[c].key)===f)return e;return a},clear:function(){this.countField=0;this.buckets={};this.entryList=new k},remove:function(g){var a=this,f=a.compareSelector(g),e=h(f);if(!d(a.buckets,e))return;for(var b=a.buckets[e],c=0;c<b.length;c++)if(a.compareSelector(b[c].key)===f){a.entryList.remove(b[c]);b.splice(c,1);if(b.length==0)delete a.buckets[e];a.countField--;return}},count:function(){return this.countField},toEnumerable:function(){var d=this;return new c(function(){var c;return new f(function(){c=d.entryList.first},function(){if(c!=b){var d={key:c.key,value:c.value};c=c.next;return this.yieldReturn(d)}return a},g.Blank)})}};return l}(),w=function(a){var b=this;b.count=function(){return a.count()};b.get=function(b){return c.from(a.get(b))};b.contains=function(b){return a.contains(b)};b.toEnumerable=function(){return a.toEnumerable().select(function(a){return new u(a.key,a.value)})}},u=function(b,a){this.key=function(){return b};h.call(this,a)};u.prototype=new h;if(typeof define===i.Function&&define.amd)define("linqjs",[],function(){return c});else if(typeof module!==i.Undefined&&module.exports)module.exports=c;else x.Enumerable=c})(this) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// QUnit Extensions | |
// Method Chaning base assertion. | |
(function (root) { | |
if (root.Enumerable == null) { | |
throw new Error("can't find Enumerable. linq.qunit.js must load after linq.js"); | |
} | |
if ((Object.defineProperties == null)) { | |
throw new Error("linq.qunit.js supports only defined 'Object.defineProperty' browser"); | |
} | |
var Enumerable = root.Enumerable; | |
Enumerable.Assert = {}; | |
// overwrite array | |
Enumerable.Utils.extendTo(Array); | |
// defProp helper, support only modern browser | |
var defineToObject = function (methodName, value) { | |
Object.defineProperty(Object.prototype, methodName, { | |
enumerable: false, | |
configurable: true, | |
writable: true, | |
value: value | |
}); | |
}; | |
var isCollection = function (obj) { | |
if (obj instanceof Enumerable) return true; | |
if (obj instanceof Array) return true; | |
return false; | |
}; | |
var executeCode = function (action) { | |
try { | |
action(); | |
return null; | |
} | |
catch (e) { | |
return e; | |
} | |
}; | |
defineToObject("is", function (expected, message) { | |
/// <signature> | |
/// <summary>strictEqual. if "this" is Array or Enumerable then deepEqual with expected and both normalized to array.</summary> | |
/// <param name="expected" type="Object">expected value</param> | |
/// <param name="message" type="String" optional="true">assertion message</param> | |
/// <returns type="void"></returns> | |
/// </signature> | |
/// <signature> | |
/// <summary>collection deepEqual. argument is variable.</summary> | |
/// <param name="variableExpected" type="params Object[]">mulitple arguments. Usage: [1,2,3].is(1,2,3).</param> | |
/// <returns type="void"></returns> | |
/// </signature> | |
/// <signature> | |
/// <summary>ok(true). expected function is passed actual. if result is true then ok.</summary> | |
/// <param name="expected" type="Func<T,bool>">function checker, return boolean</param> | |
/// <param name="message" type="String" optional="true">assertion message</param> | |
/// <returns type="void"></returns> | |
/// </signature> | |
if (isCollection(this)) { | |
if (arguments.length <= 2 && isCollection(expected)) { | |
deepEqual(Enumerable.from(this).toArray(), Enumerable.from(expected).toArray(), message); | |
} | |
else { | |
deepEqual(Enumerable.from(this).toArray(), Enumerable.from(arguments).toArray()); | |
} | |
} | |
else { | |
if (expected instanceof Function) { | |
ok(expected(this.valueOf()), message); | |
} | |
else { | |
strictEqual(this.valueOf(), expected, message); | |
} | |
} | |
}); | |
defineToObject("isNot", function (expected, message) { | |
/// <signature> | |
/// <summary>notStrictEqual. if "this" is Array or Enumerable then notDeepEqual with expected and both normalized to array.</summary> | |
/// <param name="expected" type="Object">expected value.</param> | |
/// <param name="message" type="String" optional="true">assertion message.</param> | |
/// <returns type="void"></returns> | |
/// </signature> | |
/// <signature> | |
/// <summary>collection notDeepEqual. argument is variable.</summary> | |
/// <param name="variableExpected" type="params Object[]">variable arguments. Usage: [1,2,3].isNot(-1,2,3).</param> | |
/// <returns type="void"></returns> | |
/// </signature> | |
/// <signature> | |
/// <summary>ok(false). expected function pass actual. if result is false then ok.</summary> | |
/// <param name="expected" type="Func<T,bool>">function checker, return boolean</param> | |
/// <param name="message" type="String" optional="true">assertion message</param> | |
/// <returns type="void"></returns> | |
/// </signature> | |
if (isCollection(this)) { | |
if (arguments.length <= 2 && isCollection(expected)) { | |
notDeepEqual(Enumerable.from(this).toArray(), Enumerable.from(expected).toArray(), message); | |
} | |
else { | |
notDeepEqual(Enumerable.from(this).toArray(), Enumerable.from(arguments).toArray()); | |
} | |
} | |
else { | |
if (expected instanceof Function) { | |
ok(!expected(this.valueOf()), message); | |
} | |
else { | |
notStrictEqual(this.valueOf(), expected, message); | |
} | |
} | |
}); | |
defineToObject("isExpr", function (expression, message) { | |
/// <summary>ok(true). string expression is converted lambda. lambda is passed actual. if result is true then ok.</summary> | |
/// <param name="expression" type="String">expression string converted to function checker, lambda return boolean</param> | |
/// <param name="message" type="String" optional="true">assertion message</param> | |
/// <returns type="void"></returns> | |
ok(Enumerable.Utils.createLambda(expression)(this.valueOf()), message); | |
}); | |
defineToObject("isNotExpr", function (expression, message) { | |
/// <summary>ok(false). string expression is converted lambda. lambda is passed actual. if result is false then ok.</summary> | |
/// <param name="expression" type="String">expression string converted to function checker, lambda return boolean</param> | |
/// <param name="message" type="String" optional="true">assertion message</param> | |
/// <returns type="void"></returns> | |
ok(!Enumerable.Utils.createLambda(expression)(this.valueOf()), message); | |
}); | |
defineToObject("isTrue", function (message) { | |
/// <summary>shorthand of is(true).</summary> | |
/// <param name="message" type="String" optional="true">assertion message.</param> | |
/// <returns type="void"></returns> | |
this.is(true, message); | |
}); | |
defineToObject("isFalse", function (message) { | |
/// <summary>shorthand of is(false).</summary> | |
/// <param name="message" type="String" optional="true">assertion message.</param> | |
/// <returns type="void"></returns> | |
this.is(false, message); | |
}); | |
Enumerable.Assert.expectError = function (testAction, message) { | |
/// <summary>Throw error in testCode.</summary> | |
/// <param name="testCode" type="Action">action function.</param> | |
/// <param name="message" type="String" optional="true">assertion message.</param> | |
/// <returns type="Error"></returns> | |
var error = executeCode(testAction); | |
if (error != null) { | |
ok(true, message); | |
} | |
else { | |
ok(false, "Failed testCode does not throw error." + ((message != null) ? " Message:" + message : "")); | |
} | |
return error; | |
}; | |
defineToObject("doesNotThrow", function (testAction, message) { | |
/// <summary>Does not throw error in testCode.</summary> | |
/// <param name="testCode" type="Function">action function.</param> | |
/// <param name="message" type="String" optional="true">assertion message.</param> | |
/// <returns type="void"></returns> | |
var error = executeCode(testAction); | |
if (error != null) { | |
ok(false, "Failed testCode throws error. CatchedErrorMessage:" + error.message + ((message != null) ? " Message:" + message : "")); | |
} | |
}); | |
})(this); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// extension for RxJS | |
(function (root) { | |
if (root.Enumerable == null) { | |
throw new Error("can't find Enumerable. linq.rx.js must load after linq.js"); | |
} | |
if (root.Rx == null) { | |
throw new Error("can't find Rx. linq.rx.js must load after RxJS"); | |
} | |
var Enumerable = root.Enumerable; | |
var Rx = root.Rx; | |
Enumerable.prototype.toObservable = function (scheduler) { | |
/// <summary>Converts an enumerable sequence to an observable sequence.</summary> | |
/// <param type="Scheduler" name="scheduler" optional="true">Rx.Scheduler. Default is CurrentThread.</param> | |
var source = this; | |
if (scheduler == null) scheduler = Rx.Scheduler.currentThread; | |
return Rx.Observable.createWithDisposable(function (observer) { | |
var disposable = new Rx.SingleAssignmentDisposable(); | |
var enumerator = source.getEnumerator(); | |
var calledOnCompleted; | |
var cancelable = scheduler.scheduleRecursive(function (self) { | |
var hasNext = false; | |
var current; | |
try { | |
if (disposable.isDisposed) return; | |
hasNext = enumerator.moveNext(); | |
if (hasNext) current = enumerator.current(); | |
else enumerator.dispose(); | |
} | |
catch (e) { | |
try { | |
enumerator.dispose(); | |
} | |
finally { | |
observer.onError(e); | |
} | |
return; | |
} | |
if (hasNext) { | |
observer.onNext(current); | |
self(); // loop | |
} | |
else { | |
observer.onCompleted(); | |
} | |
}); | |
disposable.disposable(cancelable); | |
return disposable; | |
}); | |
}; | |
Rx.Observable.prototype.toEnumerable = function () { | |
/// <summary>Converts an observable sequence to an enumerable sequence. Notice:cold observable only.</summary> | |
var obs = this; | |
return Enumerable.defer(function () { | |
var array = []; | |
obs.subscribe(function (x) { array.push(x) }).dispose(); | |
return array; | |
}); | |
}; | |
})(this); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* QUnit v1.9.0pre - A JavaScript Unit Testing Framework | |
* | |
* http://docs.jquery.com/QUnit | |
* | |
* Copyright 2012 jQuery Foundation and other contributors | |
* Dual licensed under the MIT or GPL Version 2 licenses. | |
* http://jquery.org/license | |
*/ | |
(function( window ) { | |
var QUnit, | |
config, | |
onErrorFnPrev, | |
testId = 0, | |
fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""), | |
toString = Object.prototype.toString, | |
hasOwn = Object.prototype.hasOwnProperty, | |
defined = { | |
setTimeout: typeof window.setTimeout !== "undefined", | |
sessionStorage: (function() { | |
var x = "qunit-test-string"; | |
try { | |
sessionStorage.setItem( x, x ); | |
sessionStorage.removeItem( x ); | |
return true; | |
} catch( e ) { | |
return false; | |
} | |
}()) | |
}; | |
function Test( settings ) { | |
extend( this, settings ); | |
this.assertions = []; | |
this.testNumber = ++Test.count; | |
} | |
Test.count = 0; | |
Test.prototype = { | |
init: function() { | |
var a, b, li, | |
tests = id( "qunit-tests" ); | |
if ( tests ) { | |
b = document.createElement( "strong" ); | |
b.innerHTML = this.name; | |
// `a` initialized at top of scope | |
a = document.createElement( "a" ); | |
a.innerHTML = "Rerun"; | |
a.href = QUnit.url({ testNumber: this.testNumber }); | |
li = document.createElement( "li" ); | |
li.appendChild( b ); | |
li.appendChild( a ); | |
li.className = "running"; | |
li.id = this.id = "qunit-test-output" + testId++; | |
tests.appendChild( li ); | |
} | |
}, | |
setup: function() { | |
if ( this.module !== config.previousModule ) { | |
if ( config.previousModule ) { | |
runLoggingCallbacks( "moduleDone", QUnit, { | |
name: config.previousModule, | |
failed: config.moduleStats.bad, | |
passed: config.moduleStats.all - config.moduleStats.bad, | |
total: config.moduleStats.all | |
}); | |
} | |
config.previousModule = this.module; | |
config.moduleStats = { all: 0, bad: 0 }; | |
runLoggingCallbacks( "moduleStart", QUnit, { | |
name: this.module | |
}); | |
} else if ( config.autorun ) { | |
runLoggingCallbacks( "moduleStart", QUnit, { | |
name: this.module | |
}); | |
} | |
config.current = this; | |
this.testEnvironment = extend({ | |
setup: function() {}, | |
teardown: function() {} | |
}, this.moduleTestEnvironment ); | |
runLoggingCallbacks( "testStart", QUnit, { | |
name: this.testName, | |
module: this.module | |
}); | |
// allow utility functions to access the current test environment | |
// TODO why?? | |
QUnit.current_testEnvironment = this.testEnvironment; | |
if ( !config.pollution ) { | |
saveGlobal(); | |
} | |
if ( config.notrycatch ) { | |
this.testEnvironment.setup.call( this.testEnvironment ); | |
return; | |
} | |
try { | |
this.testEnvironment.setup.call( this.testEnvironment ); | |
} catch( e ) { | |
QUnit.pushFailure( "Setup failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); | |
} | |
}, | |
run: function() { | |
config.current = this; | |
var running = id( "qunit-testresult" ); | |
if ( running ) { | |
running.innerHTML = "Running: <br/>" + this.name; | |
} | |
if ( this.async ) { | |
QUnit.stop(); | |
} | |
if ( config.notrycatch ) { | |
this.callback.call( this.testEnvironment, QUnit.assert ); | |
return; | |
} | |
try { | |
this.callback.call( this.testEnvironment, QUnit.assert ); | |
} catch( e ) { | |
QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + e.message, extractStacktrace( e, 0 ) ); | |
// else next test will carry the responsibility | |
saveGlobal(); | |
// Restart the tests if they're blocking | |
if ( config.blocking ) { | |
QUnit.start(); | |
} | |
} | |
}, | |
teardown: function() { | |
config.current = this; | |
if ( config.notrycatch ) { | |
this.testEnvironment.teardown.call( this.testEnvironment ); | |
return; | |
} else { | |
try { | |
this.testEnvironment.teardown.call( this.testEnvironment ); | |
} catch( e ) { | |
QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); | |
} | |
} | |
checkPollution(); | |
}, | |
finish: function() { | |
config.current = this; | |
if ( config.requireExpects && this.expected == null ) { | |
QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); | |
} else if ( this.expected != null && this.expected != this.assertions.length ) { | |
QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); | |
} else if ( this.expected == null && !this.assertions.length ) { | |
QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); | |
} | |
var assertion, a, b, i, li, ol, | |
test = this, | |
good = 0, | |
bad = 0, | |
tests = id( "qunit-tests" ); | |
config.stats.all += this.assertions.length; | |
config.moduleStats.all += this.assertions.length; | |
if ( tests ) { | |
ol = document.createElement( "ol" ); | |
for ( i = 0; i < this.assertions.length; i++ ) { | |
assertion = this.assertions[i]; | |
li = document.createElement( "li" ); | |
li.className = assertion.result ? "pass" : "fail"; | |
li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" ); | |
ol.appendChild( li ); | |
if ( assertion.result ) { | |
good++; | |
} else { | |
bad++; | |
config.stats.bad++; | |
config.moduleStats.bad++; | |
} | |
} | |
// store result when possible | |
if ( QUnit.config.reorder && defined.sessionStorage ) { | |
if ( bad ) { | |
sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad ); | |
} else { | |
sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName ); | |
} | |
} | |
if ( bad === 0 ) { | |
ol.style.display = "none"; | |
} | |
// `b` initialized at top of scope | |
b = document.createElement( "strong" ); | |
b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; | |
addEvent(b, "click", function() { | |
var next = b.nextSibling.nextSibling, | |
display = next.style.display; | |
next.style.display = display === "none" ? "block" : "none"; | |
}); | |
addEvent(b, "dblclick", function( e ) { | |
var target = e && e.target ? e.target : window.event.srcElement; | |
if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { | |
target = target.parentNode; | |
} | |
if ( window.location && target.nodeName.toLowerCase() === "strong" ) { | |
window.location = QUnit.url({ testNumber: test.testNumber }); | |
} | |
}); | |
// `li` initialized at top of scope | |
li = id( this.id ); | |
li.className = bad ? "fail" : "pass"; | |
li.removeChild( li.firstChild ); | |
a = li.firstChild; | |
li.appendChild( b ); | |
li.appendChild ( a ); | |
li.appendChild( ol ); | |
} else { | |
for ( i = 0; i < this.assertions.length; i++ ) { | |
if ( !this.assertions[i].result ) { | |
bad++; | |
config.stats.bad++; | |
config.moduleStats.bad++; | |
} | |
} | |
} | |
runLoggingCallbacks( "testDone", QUnit, { | |
name: this.testName, | |
module: this.module, | |
failed: bad, | |
passed: this.assertions.length - bad, | |
total: this.assertions.length | |
}); | |
QUnit.reset(); | |
config.current = undefined; | |
}, | |
queue: function() { | |
var bad, | |
test = this; | |
synchronize(function() { | |
test.init(); | |
}); | |
function run() { | |
// each of these can by async | |
synchronize(function() { | |
test.setup(); | |
}); | |
synchronize(function() { | |
test.run(); | |
}); | |
synchronize(function() { | |
test.teardown(); | |
}); | |
synchronize(function() { | |
test.finish(); | |
}); | |
} | |
// `bad` initialized at top of scope | |
// defer when previous test run passed, if storage is available | |
bad = QUnit.config.reorder && defined.sessionStorage && | |
+sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); | |
if ( bad ) { | |
run(); | |
} else { | |
synchronize( run, true ); | |
} | |
} | |
}; | |
// Root QUnit object. | |
// `QUnit` initialized at top of scope | |
QUnit = { | |
// call on start of module test to prepend name to all tests | |
module: function( name, testEnvironment ) { | |
config.currentModule = name; | |
config.currentModuleTestEnviroment = testEnvironment; | |
}, | |
asyncTest: function( testName, expected, callback ) { | |
if ( arguments.length === 2 ) { | |
callback = expected; | |
expected = null; | |
} | |
QUnit.test( testName, expected, callback, true ); | |
}, | |
test: function( testName, expected, callback, async ) { | |
var test, | |
name = "<span class='test-name'>" + escapeInnerText( testName ) + "</span>"; | |
if ( arguments.length === 2 ) { | |
callback = expected; | |
expected = null; | |
} | |
if ( config.currentModule ) { | |
name = "<span class='module-name'>" + config.currentModule + "</span>: " + name; | |
} | |
test = new Test({ | |
name: name, | |
testName: testName, | |
expected: expected, | |
async: async, | |
callback: callback, | |
module: config.currentModule, | |
moduleTestEnvironment: config.currentModuleTestEnviroment, | |
stack: sourceFromStacktrace( 2 ) | |
}); | |
if ( !validTest( test ) ) { | |
return; | |
} | |
test.queue(); | |
}, | |
// Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. | |
expect: function( asserts ) { | |
config.current.expected = asserts; | |
}, | |
start: function( count ) { | |
config.semaphore -= count || 1; | |
// don't start until equal number of stop-calls | |
if ( config.semaphore > 0 ) { | |
return; | |
} | |
// ignore if start is called more often then stop | |
if ( config.semaphore < 0 ) { | |
config.semaphore = 0; | |
} | |
// A slight delay, to avoid any current callbacks | |
if ( defined.setTimeout ) { | |
window.setTimeout(function() { | |
if ( config.semaphore > 0 ) { | |
return; | |
} | |
if ( config.timeout ) { | |
clearTimeout( config.timeout ); | |
} | |
config.blocking = false; | |
process( true ); | |
}, 13); | |
} else { | |
config.blocking = false; | |
process( true ); | |
} | |
}, | |
stop: function( count ) { | |
config.semaphore += count || 1; | |
config.blocking = true; | |
if ( config.testTimeout && defined.setTimeout ) { | |
clearTimeout( config.timeout ); | |
config.timeout = window.setTimeout(function() { | |
QUnit.ok( false, "Test timed out" ); | |
config.semaphore = 1; | |
QUnit.start(); | |
}, config.testTimeout ); | |
} | |
} | |
}; | |
// Asssert helpers | |
// All of these must call either QUnit.push() or manually do: | |
// - runLoggingCallbacks( "log", .. ); | |
// - config.current.assertions.push({ .. }); | |
QUnit.assert = { | |
/** | |
* Asserts rough true-ish result. | |
* @name ok | |
* @function | |
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); | |
*/ | |
ok: function( result, msg ) { | |
if ( !config.current ) { | |
throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) ); | |
} | |
result = !!result; | |
var source, | |
details = { | |
result: result, | |
message: msg | |
}; | |
msg = escapeInnerText( msg || (result ? "okay" : "failed" ) ); | |
msg = "<span class='test-message'>" + msg + "</span>"; | |
if ( !result ) { | |
source = sourceFromStacktrace( 2 ); | |
if ( source ) { | |
details.source = source; | |
msg += "<table><tr class='test-source'><th>Source: </th><td><pre>" + escapeInnerText( source ) + "</pre></td></tr></table>"; | |
} | |
} | |
runLoggingCallbacks( "log", QUnit, details ); | |
config.current.assertions.push({ | |
result: result, | |
message: msg | |
}); | |
}, | |
/** | |
* Assert that the first two arguments are equal, with an optional message. | |
* Prints out both actual and expected values. | |
* @name equal | |
* @function | |
* @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); | |
*/ | |
equal: function( actual, expected, message ) { | |
QUnit.push( expected == actual, actual, expected, message ); | |
}, | |
/** | |
* @name notEqual | |
* @function | |
*/ | |
notEqual: function( actual, expected, message ) { | |
QUnit.push( expected != actual, actual, expected, message ); | |
}, | |
/** | |
* @name deepEqual | |
* @function | |
*/ | |
deepEqual: function( actual, expected, message ) { | |
QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); | |
}, | |
/** | |
* @name notDeepEqual | |
* @function | |
*/ | |
notDeepEqual: function( actual, expected, message ) { | |
QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); | |
}, | |
/** | |
* @name strictEqual | |
* @function | |
*/ | |
strictEqual: function( actual, expected, message ) { | |
QUnit.push( expected === actual, actual, expected, message ); | |
}, | |
/** | |
* @name notStrictEqual | |
* @function | |
*/ | |
notStrictEqual: function( actual, expected, message ) { | |
QUnit.push( expected !== actual, actual, expected, message ); | |
}, | |
throws: function( block, expected, message ) { | |
var actual, | |
ok = false; | |
// 'expected' is optional | |
if ( typeof expected === "string" ) { | |
message = expected; | |
expected = null; | |
} | |
config.current.ignoreGlobalErrors = true; | |
try { | |
block.call( config.current.testEnvironment ); | |
} catch (e) { | |
actual = e; | |
} | |
config.current.ignoreGlobalErrors = false; | |
if ( actual ) { | |
// we don't want to validate thrown error | |
if ( !expected ) { | |
ok = true; | |
// expected is a regexp | |
} else if ( QUnit.objectType( expected ) === "regexp" ) { | |
ok = expected.test( actual ); | |
// expected is a constructor | |
} else if ( actual instanceof expected ) { | |
ok = true; | |
// expected is a validation function which returns true is validation passed | |
} else if ( expected.call( {}, actual ) === true ) { | |
ok = true; | |
} | |
QUnit.push( ok, actual, null, message ); | |
} else { | |
QUnit.pushFailure( message, null, 'No exception was thrown.' ); | |
} | |
} | |
}; | |
/** | |
* @deprecate since 1.8.0 | |
* Kept assertion helpers in root for backwards compatibility | |
*/ | |
extend( QUnit, QUnit.assert ); | |
/** | |
* @deprecated since 1.9.0 | |
* Kept global "raises()" for backwards compatibility | |
*/ | |
QUnit.raises = QUnit.assert.throws; | |
/** | |
* @deprecated since 1.0.0, replaced with error pushes since 1.3.0 | |
* Kept to avoid TypeErrors for undefined methods. | |
*/ | |
QUnit.equals = function() { | |
QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" ); | |
}; | |
QUnit.same = function() { | |
QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" ); | |
}; | |
// We want access to the constructor's prototype | |
(function() { | |
function F() {} | |
F.prototype = QUnit; | |
QUnit = new F(); | |
// Make F QUnit's constructor so that we can add to the prototype later | |
QUnit.constructor = F; | |
}()); | |
/** | |
* Config object: Maintain internal state | |
* Later exposed as QUnit.config | |
* `config` initialized at top of scope | |
*/ | |
config = { | |
// The queue of tests to run | |
queue: [], | |
// block until document ready | |
blocking: true, | |
// when enabled, show only failing tests | |
// gets persisted through sessionStorage and can be changed in UI via checkbox | |
hidepassed: false, | |
// by default, run previously failed tests first | |
// very useful in combination with "Hide passed tests" checked | |
reorder: true, | |
// by default, modify document.title when suite is done | |
altertitle: true, | |
// when enabled, all tests must call expect() | |
requireExpects: false, | |
// add checkboxes that are persisted in the query-string | |
// when enabled, the id is set to `true` as a `QUnit.config` property | |
urlConfig: [ | |
{ | |
id: "noglobals", | |
label: "Check for Globals", | |
tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." | |
}, | |
{ | |
id: "notrycatch", | |
label: "No try-catch", | |
tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." | |
} | |
], | |
// logging callback queues | |
begin: [], | |
done: [], | |
log: [], | |
testStart: [], | |
testDone: [], | |
moduleStart: [], | |
moduleDone: [] | |
}; | |
// Initialize more QUnit.config and QUnit.urlParams | |
(function() { | |
var i, | |
location = window.location || { search: "", protocol: "file:" }, | |
params = location.search.slice( 1 ).split( "&" ), | |
length = params.length, | |
urlParams = {}, | |
current; | |
if ( params[ 0 ] ) { | |
for ( i = 0; i < length; i++ ) { | |
current = params[ i ].split( "=" ); | |
current[ 0 ] = decodeURIComponent( current[ 0 ] ); | |
// allow just a key to turn on a flag, e.g., test.html?noglobals | |
current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; | |
urlParams[ current[ 0 ] ] = current[ 1 ]; | |
} | |
} | |
QUnit.urlParams = urlParams; | |
// String search anywhere in moduleName+testName | |
config.filter = urlParams.filter; | |
// Exact match of the module name | |
config.module = urlParams.module; | |
config.testNumber = parseInt( urlParams.testNumber, 10 ) || null; | |
// Figure out if we're running the tests from a server or not | |
QUnit.isLocal = location.protocol === "file:"; | |
}()); | |
// Export global variables, unless an 'exports' object exists, | |
// in that case we assume we're in CommonJS (dealt with on the bottom of the script) | |
if ( typeof exports === "undefined" ) { | |
extend( window, QUnit ); | |
// Expose QUnit object | |
window.QUnit = QUnit; | |
} | |
// Extend QUnit object, | |
// these after set here because they should not be exposed as global functions | |
extend( QUnit, { | |
config: config, | |
// Initialize the configuration options | |
init: function() { | |
extend( config, { | |
stats: { all: 0, bad: 0 }, | |
moduleStats: { all: 0, bad: 0 }, | |
started: +new Date(), | |
updateRate: 1000, | |
blocking: false, | |
autostart: true, | |
autorun: false, | |
filter: "", | |
queue: [], | |
semaphore: 0 | |
}); | |
var tests, banner, result, | |
qunit = id( "qunit" ); | |
if ( qunit ) { | |
qunit.innerHTML = | |
"<h1 id='qunit-header'>" + escapeInnerText( document.title ) + "</h1>" + | |
"<h2 id='qunit-banner'></h2>" + | |
"<div id='qunit-testrunner-toolbar'></div>" + | |
"<h2 id='qunit-userAgent'></h2>" + | |
"<ol id='qunit-tests'></ol>"; | |
} | |
tests = id( "qunit-tests" ); | |
banner = id( "qunit-banner" ); | |
result = id( "qunit-testresult" ); | |
if ( tests ) { | |
tests.innerHTML = ""; | |
} | |
if ( banner ) { | |
banner.className = ""; | |
} | |
if ( result ) { | |
result.parentNode.removeChild( result ); | |
} | |
if ( tests ) { | |
result = document.createElement( "p" ); | |
result.id = "qunit-testresult"; | |
result.className = "result"; | |
tests.parentNode.insertBefore( result, tests ); | |
result.innerHTML = "Running...<br/> "; | |
} | |
}, | |
// Resets the test setup. Useful for tests that modify the DOM. | |
// If jQuery is available, uses jQuery's html(), otherwise just innerHTML. | |
reset: function() { | |
var fixture; | |
if ( window.jQuery ) { | |
jQuery( "#qunit-fixture" ).html( config.fixture ); | |
} else { | |
fixture = id( "qunit-fixture" ); | |
if ( fixture ) { | |
fixture.innerHTML = config.fixture; | |
} | |
} | |
}, | |
// Trigger an event on an element. | |
// @example triggerEvent( document.body, "click" ); | |
triggerEvent: function( elem, type, event ) { | |
if ( document.createEvent ) { | |
event = document.createEvent( "MouseEvents" ); | |
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, | |
0, 0, 0, 0, 0, false, false, false, false, 0, null); | |
elem.dispatchEvent( event ); | |
} else if ( elem.fireEvent ) { | |
elem.fireEvent( "on" + type ); | |
} | |
}, | |
// Safe object type checking | |
is: function( type, obj ) { | |
return QUnit.objectType( obj ) == type; | |
}, | |
objectType: function( obj ) { | |
if ( typeof obj === "undefined" ) { | |
return "undefined"; | |
// consider: typeof null === object | |
} | |
if ( obj === null ) { | |
return "null"; | |
} | |
var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ""; | |
switch ( type ) { | |
case "Number": | |
if ( isNaN(obj) ) { | |
return "nan"; | |
} | |
return "number"; | |
case "String": | |
case "Boolean": | |
case "Array": | |
case "Date": | |
case "RegExp": | |
case "Function": | |
return type.toLowerCase(); | |
} | |
if ( typeof obj === "object" ) { | |
return "object"; | |
} | |
return undefined; | |
}, | |
push: function( result, actual, expected, message ) { | |
if ( !config.current ) { | |
throw new Error( "assertion outside test context, was " + sourceFromStacktrace() ); | |
} | |
var output, source, | |
details = { | |
result: result, | |
message: message, | |
actual: actual, | |
expected: expected | |
}; | |
message = escapeInnerText( message ) || ( result ? "okay" : "failed" ); | |
message = "<span class='test-message'>" + message + "</span>"; | |
output = message; | |
if ( !result ) { | |
expected = escapeInnerText( QUnit.jsDump.parse(expected) ); | |
actual = escapeInnerText( QUnit.jsDump.parse(actual) ); | |
output += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + expected + "</pre></td></tr>"; | |
if ( actual != expected ) { | |
output += "<tr class='test-actual'><th>Result: </th><td><pre>" + actual + "</pre></td></tr>"; | |
output += "<tr class='test-diff'><th>Diff: </th><td><pre>" + QUnit.diff( expected, actual ) + "</pre></td></tr>"; | |
} | |
source = sourceFromStacktrace(); | |
if ( source ) { | |
details.source = source; | |
output += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeInnerText( source ) + "</pre></td></tr>"; | |
} | |
output += "</table>"; | |
} | |
runLoggingCallbacks( "log", QUnit, details ); | |
config.current.assertions.push({ | |
result: !!result, | |
message: output | |
}); | |
}, | |
pushFailure: function( message, source, actual ) { | |
if ( !config.current ) { | |
throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) ); | |
} | |
var output, | |
details = { | |
result: false, | |
message: message | |
}; | |
message = escapeInnerText( message ) || "error"; | |
message = "<span class='test-message'>" + message + "</span>"; | |
output = message; | |
output += "<table>"; | |
if ( actual ) { | |
output += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeInnerText( actual ) + "</pre></td></tr>"; | |
} | |
if ( source ) { | |
details.source = source; | |
output += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeInnerText( source ) + "</pre></td></tr>"; | |
} | |
output += "</table>"; | |
runLoggingCallbacks( "log", QUnit, details ); | |
config.current.assertions.push({ | |
result: false, | |
message: output | |
}); | |
}, | |
url: function( params ) { | |
params = extend( extend( {}, QUnit.urlParams ), params ); | |
var key, | |
querystring = "?"; | |
for ( key in params ) { | |
if ( !hasOwn.call( params, key ) ) { | |
continue; | |
} | |
querystring += encodeURIComponent( key ) + "=" + | |
encodeURIComponent( params[ key ] ) + "&"; | |
} | |
return window.location.pathname + querystring.slice( 0, -1 ); | |
}, | |
extend: extend, | |
id: id, | |
addEvent: addEvent | |
// load, equiv, jsDump, diff: Attached later | |
}); | |
/** | |
* @deprecated: Created for backwards compatibility with test runner that set the hook function | |
* into QUnit.{hook}, instead of invoking it and passing the hook function. | |
* QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. | |
* Doing this allows us to tell if the following methods have been overwritten on the actual | |
* QUnit object. | |
*/ | |
extend( QUnit.constructor.prototype, { | |
// Logging callbacks; all receive a single argument with the listed properties | |
// run test/logs.html for any related changes | |
begin: registerLoggingCallback( "begin" ), | |
// done: { failed, passed, total, runtime } | |
done: registerLoggingCallback( "done" ), | |
// log: { result, actual, expected, message } | |
log: registerLoggingCallback( "log" ), | |
// testStart: { name } | |
testStart: registerLoggingCallback( "testStart" ), | |
// testDone: { name, failed, passed, total } | |
testDone: registerLoggingCallback( "testDone" ), | |
// moduleStart: { name } | |
moduleStart: registerLoggingCallback( "moduleStart" ), | |
// moduleDone: { name, failed, passed, total } | |
moduleDone: registerLoggingCallback( "moduleDone" ) | |
}); | |
if ( typeof document === "undefined" || document.readyState === "complete" ) { | |
config.autorun = true; | |
} | |
QUnit.load = function() { | |
runLoggingCallbacks( "begin", QUnit, {} ); | |
// Initialize the config, saving the execution queue | |
var banner, filter, i, label, len, main, ol, toolbar, userAgent, val, urlConfigCheckboxes, | |
urlConfigHtml = "", | |
oldconfig = extend( {}, config ); | |
QUnit.init(); | |
extend(config, oldconfig); | |
config.blocking = false; | |
len = config.urlConfig.length; | |
for ( i = 0; i < len; i++ ) { | |
val = config.urlConfig[i]; | |
if ( typeof val === "string" ) { | |
val = { | |
id: val, | |
label: val, | |
tooltip: "[no tooltip available]" | |
}; | |
} | |
config[ val.id ] = QUnit.urlParams[ val.id ]; | |
urlConfigHtml += "<input id='qunit-urlconfig-" + val.id + "' name='" + val.id + "' type='checkbox'" + ( config[ val.id ] ? " checked='checked'" : "" ) + " title='" + val.tooltip + "'><label for='qunit-urlconfig-" + val.id + "' title='" + val.tooltip + "'>" + val.label + "</label>"; | |
} | |
// `userAgent` initialized at top of scope | |
userAgent = id( "qunit-userAgent" ); | |
if ( userAgent ) { | |
userAgent.innerHTML = navigator.userAgent; | |
} | |
// `banner` initialized at top of scope | |
banner = id( "qunit-header" ); | |
if ( banner ) { | |
banner.innerHTML = "<a href='" + QUnit.url({ filter: undefined, module: undefined, testNumber: undefined }) + "'>" + banner.innerHTML + "</a> "; | |
} | |
// `toolbar` initialized at top of scope | |
toolbar = id( "qunit-testrunner-toolbar" ); | |
if ( toolbar ) { | |
// `filter` initialized at top of scope | |
filter = document.createElement( "input" ); | |
filter.type = "checkbox"; | |
filter.id = "qunit-filter-pass"; | |
addEvent( filter, "click", function() { | |
var tmp, | |
ol = document.getElementById( "qunit-tests" ); | |
if ( filter.checked ) { | |
ol.className = ol.className + " hidepass"; | |
} else { | |
tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; | |
ol.className = tmp.replace( / hidepass /, " " ); | |
} | |
if ( defined.sessionStorage ) { | |
if (filter.checked) { | |
sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); | |
} else { | |
sessionStorage.removeItem( "qunit-filter-passed-tests" ); | |
} | |
} | |
}); | |
if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { | |
filter.checked = true; | |
// `ol` initialized at top of scope | |
ol = document.getElementById( "qunit-tests" ); | |
ol.className = ol.className + " hidepass"; | |
} | |
toolbar.appendChild( filter ); | |
// `label` initialized at top of scope | |
label = document.createElement( "label" ); | |
label.setAttribute( "for", "qunit-filter-pass" ); | |
label.setAttribute( "title", "Only show tests and assertons that fail. Stored in sessionStorage." ); | |
label.innerHTML = "Hide passed tests"; | |
toolbar.appendChild( label ); | |
urlConfigCheckboxes = document.createElement( 'span' ); | |
urlConfigCheckboxes.innerHTML = urlConfigHtml; | |
addEvent( urlConfigCheckboxes, "change", function( event ) { | |
var params = {}; | |
params[ event.target.name ] = event.target.checked ? true : undefined; | |
window.location = QUnit.url( params ); | |
}); | |
toolbar.appendChild( urlConfigCheckboxes ); | |
} | |
// `main` initialized at top of scope | |
main = id( "qunit-fixture" ); | |
if ( main ) { | |
config.fixture = main.innerHTML; | |
} | |
if ( config.autostart ) { | |
QUnit.start(); | |
} | |
}; | |
addEvent( window, "load", QUnit.load ); | |
// `onErrorFnPrev` initialized at top of scope | |
// Preserve other handlers | |
onErrorFnPrev = window.onerror; | |
// Cover uncaught exceptions | |
// Returning true will surpress the default browser handler, | |
// returning false will let it run. | |
window.onerror = function ( error, filePath, linerNr ) { | |
var ret = false; | |
if ( onErrorFnPrev ) { | |
ret = onErrorFnPrev( error, filePath, linerNr ); | |
} | |
// Treat return value as window.onerror itself does, | |
// Only do our handling if not surpressed. | |
if ( ret !== true ) { | |
if ( QUnit.config.current ) { | |
if ( QUnit.config.current.ignoreGlobalErrors ) { | |
return true; | |
} | |
QUnit.pushFailure( error, filePath + ":" + linerNr ); | |
} else { | |
QUnit.test( "global failure", function() { | |
QUnit.pushFailure( error, filePath + ":" + linerNr ); | |
}); | |
} | |
return false; | |
} | |
return ret; | |
}; | |
function done() { | |
config.autorun = true; | |
// Log the last module results | |
if ( config.currentModule ) { | |
runLoggingCallbacks( "moduleDone", QUnit, { | |
name: config.currentModule, | |
failed: config.moduleStats.bad, | |
passed: config.moduleStats.all - config.moduleStats.bad, | |
total: config.moduleStats.all | |
}); | |
} | |
var i, key, | |
banner = id( "qunit-banner" ), | |
tests = id( "qunit-tests" ), | |
runtime = +new Date() - config.started, | |
passed = config.stats.all - config.stats.bad, | |
html = [ | |
"Tests completed in ", | |
runtime, | |
" milliseconds.<br/>", | |
"<span class='passed'>", | |
passed, | |
"</span> tests of <span class='total'>", | |
config.stats.all, | |
"</span> passed, <span class='failed'>", | |
config.stats.bad, | |
"</span> failed." | |
].join( "" ); | |
if ( banner ) { | |
banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" ); | |
} | |
if ( tests ) { | |
id( "qunit-testresult" ).innerHTML = html; | |
} | |
if ( config.altertitle && typeof document !== "undefined" && document.title ) { | |
// show ✖ for good, ✔ for bad suite result in title | |
// use escape sequences in case file gets loaded with non-utf-8-charset | |
document.title = [ | |
( config.stats.bad ? "\u2716" : "\u2714" ), | |
document.title.replace( /^[\u2714\u2716] /i, "" ) | |
].join( " " ); | |
} | |
// clear own sessionStorage items if all tests passed | |
if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { | |
// `key` & `i` initialized at top of scope | |
for ( i = 0; i < sessionStorage.length; i++ ) { | |
key = sessionStorage.key( i++ ); | |
if ( key.indexOf( "qunit-test-" ) === 0 ) { | |
sessionStorage.removeItem( key ); | |
} | |
} | |
} | |
runLoggingCallbacks( "done", QUnit, { | |
failed: config.stats.bad, | |
passed: passed, | |
total: config.stats.all, | |
runtime: runtime | |
}); | |
} | |
/** @return Boolean: true if this test should be ran */ | |
function validTest( test ) { | |
var include, | |
filter = config.filter && config.filter.toLowerCase(), | |
module = config.module && config.module.toLowerCase(), | |
fullName = (test.module + ": " + test.testName).toLowerCase(); | |
if ( config.testNumber ) { | |
return test.testNumber === config.testNumber; | |
} | |
if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { | |
return false; | |
} | |
if ( !filter ) { | |
return true; | |
} | |
include = filter.charAt( 0 ) !== "!"; | |
if ( !include ) { | |
filter = filter.slice( 1 ); | |
} | |
// If the filter matches, we need to honour include | |
if ( fullName.indexOf( filter ) !== -1 ) { | |
return include; | |
} | |
// Otherwise, do the opposite | |
return !include; | |
} | |
// so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions) | |
// Later Safari and IE10 are supposed to support error.stack as well | |
// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack | |
function extractStacktrace( e, offset ) { | |
offset = offset === undefined ? 3 : offset; | |
var stack, include, i, regex; | |
if ( e.stacktrace ) { | |
// Opera | |
return e.stacktrace.split( "\n" )[ offset + 3 ]; | |
} else if ( e.stack ) { | |
// Firefox, Chrome | |
stack = e.stack.split( "\n" ); | |
if (/^error$/i.test( stack[0] ) ) { | |
stack.shift(); | |
} | |
if ( fileName ) { | |
include = []; | |
for ( i = offset; i < stack.length; i++ ) { | |
if ( stack[ i ].indexOf( fileName ) != -1 ) { | |
break; | |
} | |
include.push( stack[ i ] ); | |
} | |
if ( include.length ) { | |
return include.join( "\n" ); | |
} | |
} | |
return stack[ offset ]; | |
} else if ( e.sourceURL ) { | |
// Safari, PhantomJS | |
// hopefully one day Safari provides actual stacktraces | |
// exclude useless self-reference for generated Error objects | |
if ( /qunit.js$/.test( e.sourceURL ) ) { | |
return; | |
} | |
// for actual exceptions, this is useful | |
return e.sourceURL + ":" + e.line; | |
} | |
} | |
function sourceFromStacktrace( offset ) { | |
try { | |
throw new Error(); | |
} catch ( e ) { | |
return extractStacktrace( e, offset ); | |
} | |
} | |
function escapeInnerText( s ) { | |
if ( !s ) { | |
return ""; | |
} | |
s = s + ""; | |
return s.replace( /[\&<>]/g, function( s ) { | |
switch( s ) { | |
case "&": return "&"; | |
case "<": return "<"; | |
case ">": return ">"; | |
default: return s; | |
} | |
}); | |
} | |
function synchronize( callback, last ) { | |
config.queue.push( callback ); | |
if ( config.autorun && !config.blocking ) { | |
process( last ); | |
} | |
} | |
function process( last ) { | |
function next() { | |
process( last ); | |
} | |
var start = new Date().getTime(); | |
config.depth = config.depth ? config.depth + 1 : 1; | |
while ( config.queue.length && !config.blocking ) { | |
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { | |
config.queue.shift()(); | |
} else { | |
window.setTimeout( next, 13 ); | |
break; | |
} | |
} | |
config.depth--; | |
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { | |
done(); | |
} | |
} | |
function saveGlobal() { | |
config.pollution = []; | |
if ( config.noglobals ) { | |
for ( var key in window ) { | |
// in Opera sometimes DOM element ids show up here, ignore them | |
if ( !hasOwn.call( window, key ) || /^qunit-test-output/.test( key ) ) { | |
continue; | |
} | |
config.pollution.push( key ); | |
} | |
} | |
} | |
function checkPollution( name ) { | |
var newGlobals, | |
deletedGlobals, | |
old = config.pollution; | |
saveGlobal(); | |
newGlobals = diff( config.pollution, old ); | |
if ( newGlobals.length > 0 ) { | |
QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); | |
} | |
deletedGlobals = diff( old, config.pollution ); | |
if ( deletedGlobals.length > 0 ) { | |
QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); | |
} | |
} | |
// returns a new Array with the elements that are in a but not in b | |
function diff( a, b ) { | |
var i, j, | |
result = a.slice(); | |
for ( i = 0; i < result.length; i++ ) { | |
for ( j = 0; j < b.length; j++ ) { | |
if ( result[i] === b[j] ) { | |
result.splice( i, 1 ); | |
i--; | |
break; | |
} | |
} | |
} | |
return result; | |
} | |
function extend( a, b ) { | |
for ( var prop in b ) { | |
if ( b[ prop ] === undefined ) { | |
delete a[ prop ]; | |
// Avoid "Member not found" error in IE8 caused by setting window.constructor | |
} else if ( prop !== "constructor" || a !== window ) { | |
a[ prop ] = b[ prop ]; | |
} | |
} | |
return a; | |
} | |
function addEvent( elem, type, fn ) { | |
if ( elem.addEventListener ) { | |
elem.addEventListener( type, fn, false ); | |
} else if ( elem.attachEvent ) { | |
elem.attachEvent( "on" + type, fn ); | |
} else { | |
fn(); | |
} | |
} | |
function id( name ) { | |
return !!( typeof document !== "undefined" && document && document.getElementById ) && | |
document.getElementById( name ); | |
} | |
function registerLoggingCallback( key ) { | |
return function( callback ) { | |
config[key].push( callback ); | |
}; | |
} | |
// Supports deprecated method of completely overwriting logging callbacks | |
function runLoggingCallbacks( key, scope, args ) { | |
//debugger; | |
var i, callbacks; | |
if ( QUnit.hasOwnProperty( key ) ) { | |
QUnit[ key ].call(scope, args ); | |
} else { | |
callbacks = config[ key ]; | |
for ( i = 0; i < callbacks.length; i++ ) { | |
callbacks[ i ].call( scope, args ); | |
} | |
} | |
} | |
// Test for equality any JavaScript type. | |
// Author: Philippe Rathé <[email protected]> | |
QUnit.equiv = (function() { | |
// Call the o related callback with the given arguments. | |
function bindCallbacks( o, callbacks, args ) { | |
var prop = QUnit.objectType( o ); | |
if ( prop ) { | |
if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { | |
return callbacks[ prop ].apply( callbacks, args ); | |
} else { | |
return callbacks[ prop ]; // or undefined | |
} | |
} | |
} | |
// the real equiv function | |
var innerEquiv, | |
// stack to decide between skip/abort functions | |
callers = [], | |
// stack to avoiding loops from circular referencing | |
parents = [], | |
getProto = Object.getPrototypeOf || function ( obj ) { | |
return obj.__proto__; | |
}, | |
callbacks = (function () { | |
// for string, boolean, number and null | |
function useStrictEquality( b, a ) { | |
if ( b instanceof a.constructor || a instanceof b.constructor ) { | |
// to catch short annotaion VS 'new' annotation of a | |
// declaration | |
// e.g. var i = 1; | |
// var j = new Number(1); | |
return a == b; | |
} else { | |
return a === b; | |
} | |
} | |
return { | |
"string": useStrictEquality, | |
"boolean": useStrictEquality, | |
"number": useStrictEquality, | |
"null": useStrictEquality, | |
"undefined": useStrictEquality, | |
"nan": function( b ) { | |
return isNaN( b ); | |
}, | |
"date": function( b, a ) { | |
return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); | |
}, | |
"regexp": function( b, a ) { | |
return QUnit.objectType( b ) === "regexp" && | |
// the regex itself | |
a.source === b.source && | |
// and its modifers | |
a.global === b.global && | |
// (gmi) ... | |
a.ignoreCase === b.ignoreCase && | |
a.multiline === b.multiline; | |
}, | |
// - skip when the property is a method of an instance (OOP) | |
// - abort otherwise, | |
// initial === would have catch identical references anyway | |
"function": function() { | |
var caller = callers[callers.length - 1]; | |
return caller !== Object && typeof caller !== "undefined"; | |
}, | |
"array": function( b, a ) { | |
var i, j, len, loop; | |
// b could be an object literal here | |
if ( QUnit.objectType( b ) !== "array" ) { | |
return false; | |
} | |
len = a.length; | |
if ( len !== b.length ) { | |
// safe and faster | |
return false; | |
} | |
// track reference to avoid circular references | |
parents.push( a ); | |
for ( i = 0; i < len; i++ ) { | |
loop = false; | |
for ( j = 0; j < parents.length; j++ ) { | |
if ( parents[j] === a[i] ) { | |
loop = true;// dont rewalk array | |
} | |
} | |
if ( !loop && !innerEquiv(a[i], b[i]) ) { | |
parents.pop(); | |
return false; | |
} | |
} | |
parents.pop(); | |
return true; | |
}, | |
"object": function( b, a ) { | |
var i, j, loop, | |
// Default to true | |
eq = true, | |
aProperties = [], | |
bProperties = []; | |
// comparing constructors is more strict than using | |
// instanceof | |
if ( a.constructor !== b.constructor ) { | |
// Allow objects with no prototype to be equivalent to | |
// objects with Object as their constructor. | |
if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) || | |
( getProto(b) === null && getProto(a) === Object.prototype ) ) ) { | |
return false; | |
} | |
} | |
// stack constructor before traversing properties | |
callers.push( a.constructor ); | |
// track reference to avoid circular references | |
parents.push( a ); | |
for ( i in a ) { // be strict: don't ensures hasOwnProperty | |
// and go deep | |
loop = false; | |
for ( j = 0; j < parents.length; j++ ) { | |
if ( parents[j] === a[i] ) { | |
// don't go down the same path twice | |
loop = true; | |
} | |
} | |
aProperties.push(i); // collect a's properties | |
if (!loop && !innerEquiv( a[i], b[i] ) ) { | |
eq = false; | |
break; | |
} | |
} | |
callers.pop(); // unstack, we are done | |
parents.pop(); | |
for ( i in b ) { | |
bProperties.push( i ); // collect b's properties | |
} | |
// Ensures identical properties name | |
return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); | |
} | |
}; | |
}()); | |
innerEquiv = function() { // can take multiple arguments | |
var args = [].slice.apply( arguments ); | |
if ( args.length < 2 ) { | |
return true; // end transition | |
} | |
return (function( a, b ) { | |
if ( a === b ) { | |
return true; // catch the most you can | |
} else if ( a === null || b === null || typeof a === "undefined" || | |
typeof b === "undefined" || | |
QUnit.objectType(a) !== QUnit.objectType(b) ) { | |
return false; // don't lose time with error prone cases | |
} else { | |
return bindCallbacks(a, callbacks, [ b, a ]); | |
} | |
// apply transition with (1..n) arguments | |
}( args[0], args[1] ) && arguments.callee.apply( this, args.splice(1, args.length - 1 )) ); | |
}; | |
return innerEquiv; | |
}()); | |
/** | |
* jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | | |
* http://flesler.blogspot.com Licensed under BSD | |
* (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 | |
* | |
* @projectDescription Advanced and extensible data dumping for Javascript. | |
* @version 1.0.0 | |
* @author Ariel Flesler | |
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} | |
*/ | |
QUnit.jsDump = (function() { | |
function quote( str ) { | |
return '"' + str.toString().replace( /"/g, '\\"' ) + '"'; | |
} | |
function literal( o ) { | |
return o + ""; | |
} | |
function join( pre, arr, post ) { | |
var s = jsDump.separator(), | |
base = jsDump.indent(), | |
inner = jsDump.indent(1); | |
if ( arr.join ) { | |
arr = arr.join( "," + s + inner ); | |
} | |
if ( !arr ) { | |
return pre + post; | |
} | |
return [ pre, inner + arr, base + post ].join(s); | |
} | |
function array( arr, stack ) { | |
var i = arr.length, ret = new Array(i); | |
this.up(); | |
while ( i-- ) { | |
ret[i] = this.parse( arr[i] , undefined , stack); | |
} | |
this.down(); | |
return join( "[", ret, "]" ); | |
} | |
var reName = /^function (\w+)/, | |
jsDump = { | |
parse: function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance | |
stack = stack || [ ]; | |
var inStack, res, | |
parser = this.parsers[ type || this.typeOf(obj) ]; | |
type = typeof parser; | |
inStack = inArray( obj, stack ); | |
if ( inStack != -1 ) { | |
return "recursion(" + (inStack - stack.length) + ")"; | |
} | |
//else | |
if ( type == "function" ) { | |
stack.push( obj ); | |
res = parser.call( this, obj, stack ); | |
stack.pop(); | |
return res; | |
} | |
// else | |
return ( type == "string" ) ? parser : this.parsers.error; | |
}, | |
typeOf: function( obj ) { | |
var type; | |
if ( obj === null ) { | |
type = "null"; | |
} else if ( typeof obj === "undefined" ) { | |
type = "undefined"; | |
} else if ( QUnit.is( "regexp", obj) ) { | |
type = "regexp"; | |
} else if ( QUnit.is( "date", obj) ) { | |
type = "date"; | |
} else if ( QUnit.is( "function", obj) ) { | |
type = "function"; | |
} else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { | |
type = "window"; | |
} else if ( obj.nodeType === 9 ) { | |
type = "document"; | |
} else if ( obj.nodeType ) { | |
type = "node"; | |
} else if ( | |
// native arrays | |
toString.call( obj ) === "[object Array]" || | |
// NodeList objects | |
( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) | |
) { | |
type = "array"; | |
} else { | |
type = typeof obj; | |
} | |
return type; | |
}, | |
separator: function() { | |
return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? " " : " "; | |
}, | |
indent: function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing | |
if ( !this.multiline ) { | |
return ""; | |
} | |
var chr = this.indentChar; | |
if ( this.HTML ) { | |
chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); | |
} | |
return new Array( this._depth_ + (extra||0) ).join(chr); | |
}, | |
up: function( a ) { | |
this._depth_ += a || 1; | |
}, | |
down: function( a ) { | |
this._depth_ -= a || 1; | |
}, | |
setParser: function( name, parser ) { | |
this.parsers[name] = parser; | |
}, | |
// The next 3 are exposed so you can use them | |
quote: quote, | |
literal: literal, | |
join: join, | |
// | |
_depth_: 1, | |
// This is the list of parsers, to modify them, use jsDump.setParser | |
parsers: { | |
window: "[Window]", | |
document: "[Document]", | |
error: "[ERROR]", //when no parser is found, shouldn"t happen | |
unknown: "[Unknown]", | |
"null": "null", | |
"undefined": "undefined", | |
"function": function( fn ) { | |
var ret = "function", | |
name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];//functions never have name in IE | |
if ( name ) { | |
ret += " " + name; | |
} | |
ret += "( "; | |
ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" ); | |
return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" ); | |
}, | |
array: array, | |
nodelist: array, | |
"arguments": array, | |
object: function( map, stack ) { | |
var ret = [ ], keys, key, val, i; | |
QUnit.jsDump.up(); | |
if ( Object.keys ) { | |
keys = Object.keys( map ); | |
} else { | |
keys = []; | |
for ( key in map ) { | |
keys.push( key ); | |
} | |
} | |
keys.sort(); | |
for ( i = 0; i < keys.length; i++ ) { | |
key = keys[ i ]; | |
val = map[ key ]; | |
ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) ); | |
} | |
QUnit.jsDump.down(); | |
return join( "{", ret, "}" ); | |
}, | |
node: function( node ) { | |
var a, val, | |
open = QUnit.jsDump.HTML ? "<" : "<", | |
close = QUnit.jsDump.HTML ? ">" : ">", | |
tag = node.nodeName.toLowerCase(), | |
ret = open + tag; | |
for ( a in QUnit.jsDump.DOMAttrs ) { | |
val = node[ QUnit.jsDump.DOMAttrs[a] ]; | |
if ( val ) { | |
ret += " " + a + "=" + QUnit.jsDump.parse( val, "attribute" ); | |
} | |
} | |
return ret + close + open + "/" + tag + close; | |
}, | |
functionArgs: function( fn ) {//function calls it internally, it's the arguments part of the function | |
var args, | |
l = fn.length; | |
if ( !l ) { | |
return ""; | |
} | |
args = new Array(l); | |
while ( l-- ) { | |
args[l] = String.fromCharCode(97+l);//97 is 'a' | |
} | |
return " " + args.join( ", " ) + " "; | |
}, | |
key: quote, //object calls it internally, the key part of an item in a map | |
functionCode: "[code]", //function calls it internally, it's the content of the function | |
attribute: quote, //node calls it internally, it's an html attribute value | |
string: quote, | |
date: quote, | |
regexp: literal, //regex | |
number: literal, | |
"boolean": literal | |
}, | |
DOMAttrs: { | |
//attributes to dump from nodes, name=>realName | |
id: "id", | |
name: "name", | |
"class": "className" | |
}, | |
HTML: false,//if true, entities are escaped ( <, >, \t, space and \n ) | |
indentChar: " ",//indentation unit | |
multiline: true //if true, items in a collection, are separated by a \n, else just a space. | |
}; | |
return jsDump; | |
}()); | |
// from Sizzle.js | |
function getText( elems ) { | |
var i, elem, | |
ret = ""; | |
for ( i = 0; elems[i]; i++ ) { | |
elem = elems[i]; | |
// Get the text from text nodes and CDATA nodes | |
if ( elem.nodeType === 3 || elem.nodeType === 4 ) { | |
ret += elem.nodeValue; | |
// Traverse everything else, except comment nodes | |
} else if ( elem.nodeType !== 8 ) { | |
ret += getText( elem.childNodes ); | |
} | |
} | |
return ret; | |
} | |
// from jquery.js | |
function inArray( elem, array ) { | |
if ( array.indexOf ) { | |
return array.indexOf( elem ); | |
} | |
for ( var i = 0, length = array.length; i < length; i++ ) { | |
if ( array[ i ] === elem ) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
/* | |
* Javascript Diff Algorithm | |
* By John Resig (http://ejohn.org/) | |
* Modified by Chu Alan "sprite" | |
* | |
* Released under the MIT license. | |
* | |
* More Info: | |
* http://ejohn.org/projects/javascript-diff-algorithm/ | |
* | |
* Usage: QUnit.diff(expected, actual) | |
* | |
* QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" | |
*/ | |
QUnit.diff = (function() { | |
function diff( o, n ) { | |
var i, | |
ns = {}, | |
os = {}; | |
for ( i = 0; i < n.length; i++ ) { | |
if ( ns[ n[i] ] == null ) { | |
ns[ n[i] ] = { | |
rows: [], | |
o: null | |
}; | |
} | |
ns[ n[i] ].rows.push( i ); | |
} | |
for ( i = 0; i < o.length; i++ ) { | |
if ( os[ o[i] ] == null ) { | |
os[ o[i] ] = { | |
rows: [], | |
n: null | |
}; | |
} | |
os[ o[i] ].rows.push( i ); | |
} | |
for ( i in ns ) { | |
if ( !hasOwn.call( ns, i ) ) { | |
continue; | |
} | |
if ( ns[i].rows.length == 1 && typeof os[i] != "undefined" && os[i].rows.length == 1 ) { | |
n[ ns[i].rows[0] ] = { | |
text: n[ ns[i].rows[0] ], | |
row: os[i].rows[0] | |
}; | |
o[ os[i].rows[0] ] = { | |
text: o[ os[i].rows[0] ], | |
row: ns[i].rows[0] | |
}; | |
} | |
} | |
for ( i = 0; i < n.length - 1; i++ ) { | |
if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null && | |
n[ i + 1 ] == o[ n[i].row + 1 ] ) { | |
n[ i + 1 ] = { | |
text: n[ i + 1 ], | |
row: n[i].row + 1 | |
}; | |
o[ n[i].row + 1 ] = { | |
text: o[ n[i].row + 1 ], | |
row: i + 1 | |
}; | |
} | |
} | |
for ( i = n.length - 1; i > 0; i-- ) { | |
if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null && | |
n[ i - 1 ] == o[ n[i].row - 1 ]) { | |
n[ i - 1 ] = { | |
text: n[ i - 1 ], | |
row: n[i].row - 1 | |
}; | |
o[ n[i].row - 1 ] = { | |
text: o[ n[i].row - 1 ], | |
row: i - 1 | |
}; | |
} | |
} | |
return { | |
o: o, | |
n: n | |
}; | |
} | |
return function( o, n ) { | |
o = o.replace( /\s+$/, "" ); | |
n = n.replace( /\s+$/, "" ); | |
var i, pre, | |
str = "", | |
out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ), | |
oSpace = o.match(/\s+/g), | |
nSpace = n.match(/\s+/g); | |
if ( oSpace == null ) { | |
oSpace = [ " " ]; | |
} | |
else { | |
oSpace.push( " " ); | |
} | |
if ( nSpace == null ) { | |
nSpace = [ " " ]; | |
} | |
else { | |
nSpace.push( " " ); | |
} | |
if ( out.n.length === 0 ) { | |
for ( i = 0; i < out.o.length; i++ ) { | |
str += "<del>" + out.o[i] + oSpace[i] + "</del>"; | |
} | |
} | |
else { | |
if ( out.n[0].text == null ) { | |
for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) { | |
str += "<del>" + out.o[n] + oSpace[n] + "</del>"; | |
} | |
} | |
for ( i = 0; i < out.n.length; i++ ) { | |
if (out.n[i].text == null) { | |
str += "<ins>" + out.n[i] + nSpace[i] + "</ins>"; | |
} | |
else { | |
// `pre` initialized at top of scope | |
pre = ""; | |
for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) { | |
pre += "<del>" + out.o[n] + oSpace[n] + "</del>"; | |
} | |
str += " " + out.n[i].text + nSpace[i] + pre; | |
} | |
} | |
} | |
return str; | |
}; | |
}()); | |
// for CommonJS enviroments, export everything | |
if ( typeof exports !== "undefined" ) { | |
extend(exports, QUnit); | |
} | |
// get at whatever the global object is, like window in browsers | |
}( (function() {return this;}.call()) )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment