Permalink
Browse files

Updated for jslint; fixed confusing code; reformatted

  • Loading branch information...
1 parent 896a012 commit 0287ffd31bd46f3f4bb05e54a5e751b223ef12fe @snapadmin snapadmin committed Aug 7, 2012
Showing with 438 additions and 420 deletions.
  1. +0 −81 README.md
  2. +0 −1 taffy-min.js
  3. +84 −0 taffy-test.html
  4. +354 −338 taffy.js
View
81 README.md
@@ -1,81 +0,0 @@
-# TaffyDB (taffy.js)
-
-TaffyDB is an open source library that brings database features into your JavaScript applications.
-
-## Introduction
-
-How you ever noticed how JavaScript object literals look a lot like records? And that if you wrap a group of them up in an array you have something that atcs a lot like a database table? TaffyDB brings powerful database funtionality to that concept and rapidly improves the way you work with data inside of JavaScript.
-
-## What makes it sticky
-
- - Extremely fast
- - Powerful JavaScript centric data selection engine
- - Database inspired features such as insert, update, unique, count, etc
- - Robust cross browser support
- - Easily extended with your own functions
- - Compatible with any DOM library (jQuery, YUI, Dojo, etc)
- - Compatible with CommonJS (node.js, etc)
-
-## Create a DB
-
-Just pass in JSON:
-
- var products = TAFFY([{
- "item":1,
- "name":"Blue Ray Player",
- "price":99.99
- }, {
- "item":2,
- name:"3D TV",
- price:1799.99
- }]);
-
-
-## Find data
-
-Use JSON to compare:
-
- var item1 = products({item:1});
- // where item is equal to 1
- var lowPricedItems = products({price:{lt:100}});
- // where price is less than 100
- var blueRayPlayers = products({name:{like:"Blue Ray"}});
- // where name is like "Blue Ray"
-
-## Use data
-
- // update the price of the Blue Ray Player to 89.99
- products({item:1}).update({price:89.99});
- // loop over the records and call a function
- products().each(function (r) {alert(r.name)});
- // get first record
- products().first();
- // get last record
- products().last();
- // sort the records by price descending
- products.sort("price desc");
- // select only the item names into an array
- products().select("name"); // returns ["3D TV","Blue Ray Player"]
- // inject values from a record into a string template
- var row = products({item:2}).supplant("<tr><td>{name}</td><td>{price}</td></tr>");
- // row now equal to "<tr><td>3D TV</td><td>17999.99</td></tr>"
-
-## Documentation, support, updates
-
-View more docs and examples, get support, and get notified of updates:
-
-Web: http://taffydb.com
-Twitter: http://twitter.com/mriansmith
-
-
-## Software License Agreement (BSD License)
-Copyright (c)
-All rights reserved.
-
-
-Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following condition is met:
-
-* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
View
1 taffy-min.js
@@ -1 +0,0 @@
-var TAFFY,exports;(function(){if(!TAFFY){var j="2.6.1",m=1,a="000000",n=1000,c={},i,l,b,h,e,g,o,k;i=function(p){if(TAFFY.isArray(p)||TAFFY.isObject(p)){return p}else{return JSON.parse(p)}};l=function(s,q,t){var w,v,p,z;if(s&&((f.isArray(s)&&s.length===1)||(!f.isArray(s)))){q((f.isArray(s))?s[0]:s,0)}else{for(w,v,p=0,s=(f.isArray(s))?s:[s],z=s.length;p<z;p++){v=s[p];if(!f.isUndefined(v)||(t||false)){w=q(v,p);if(w===f.EXIT){break}}}}};b=function(u,q){var p=0,t,s;for(s in u){if(u.hasOwnProperty(s)){t=q(u[s],s,p++);if(t===f.EXIT){break}}}};c.extend=function(p,q){c[p]=function(){return q.apply(this,arguments)}};h=function(q){if(f.isString(q)&&/[t][0-9]*[r][0-9]*/i.test(q)){return true}if(f.isObject(q)&&q.___id&&q.___s){return true}if(f.isArray(q)){var p=true;l(q,function(s){if(!h(s)){p=false;return TAFFY.EXIT}});return p}return false};g=function(s,q){var p=true;l(q,function(r){switch(f.typeOf(r)){case"function":if(!r.apply(s)){p=false;return TAFFY.EXIT}break;case"array":p=(r.length===1)?(g(s,r[0])):(r.length===2)?(g(s,r[0])||g(s,r[1])):(r.length===3)?(g(s,r[0])||g(s,r[1])||g(s,r[2])):(r.length===4)?(g(s,r[0])||g(s,r[1])||g(s,r[2])||g(s,r[3])):false;if(r.length>4){l(r,function(t){if(g(s,t)){p=true}})}break}});return p};e=function(q){var p=[];if(f.isString(q)&&/[t][0-9]*[r][0-9]*/i.test(q)){q={___id:q}}if(f.isArray(q)){l(q,function(s){p.push(e(s))});q=function(){var s=this;var r=false;l(p,function(t){if(g(s,t)){r=true}});return r};return q}if(f.isObject(q)){if(f.isObject(q)&&q.___id&&q.___s){q={___id:q.___id}}b(q,function(r,s){if(!f.isObject(r)){r={is:r}}b(r,function(t,u){var w=[];var v=(u==="hasAll")?function(x,y){y(x)}:l;v(t,function(y){var x=true,z=false;var A=function(){var F=this[s],E="==",G="!=",I="===",J="<",D=">",K="<=",H=">=",C="!==",B;if((u.indexOf("!")===0)&&u!==G&&u!==C){x=false;u=u.substring(1,u.length)}B=((u==="regex")?(y.test(F)):(u==="lt"||u===J)?(F<y):(u==="gt"||u===D)?(F>y):(u==="lte"||u===K)?(F<=y):(u==="gte"||u===H)?(F>=y):(u==="left")?(F.indexOf(y)===0):(u==="leftnocase")?(F.toLowerCase().indexOf(y.toLowerCase())===0):(u==="right")?(F.substring((F.length-y.length))===y):(u==="rightnocase")?(F.toLowerCase().substring((F.length-y.length))===y.toLowerCase()):(u==="like")?(F.indexOf(y)>=0):(u==="likenocase")?(F.toLowerCase().indexOf(y.toLowerCase())>=0):(u===I||u==="is")?(F===y):(u===E)?(F==y):(u===C)?(F!==y):(u===G)?(F!=y):(u==="isnocase")?(F.toLowerCase?F.toLowerCase()===y.toLowerCase():F===y):(u==="has")?(f.has(F,y)):(u==="hasall")?(f.hasAll(F,y)):(u.indexOf("is")===-1&&!TAFFY.isNull(F)&&!TAFFY.isUndefined(F)&&!TAFFY.isObject(y)&&!TAFFY.isArray(y))?(y===F[u]):(f[u]&&f.isFunction(f[u])&&u.indexOf("is")===0)?f[u](F)===y:(f[u]&&f.isFunction(f[u]))?f[u](F,y):(false));B=(B&&!x)?false:(!B&&!x)?true:B;return B};w.push(A)});if(w.length===1){p.push(w[0])}else{p.push(function(){var y=this;var x=false;l(w,function(z){if(z.apply(y)){x=true}});return x})}})});q=function(){var s=this,r=true;r=(p.length===1&&!p[0].apply(s))?false:(p.length===2&&(!p[0].apply(s)||!p[1].apply(s)))?false:(p.length===3&&(!p[0].apply(s)||!p[1].apply(s)||!p[2].apply(s)))?false:(p.length===4&&(!p[0].apply(s)||!p[1].apply(s)||!p[2].apply(s)||!p[3].apply(s)))?false:true;if(p.length>4){l(p,function(t){if(!g(s,t)){r=false}})}return r};return q}if(f.isFunction(q)){return q}};k=function(p,q){var r=function(t,s){var u=0;f.each(q,function(x){var z=x.split(" ");var w=z[0];var v=(z.length===1)?"logical":z[1];if(v==="logical"){var A=o(t[w]),y=o(s[w]);f.each((A.length<=y.length)?A:y,function(B,C){if(A[C]<y[C]){u=-1;return TAFFY.EXIT}else{if(A[C]>y[C]){u=1;return TAFFY.EXIT}}})}else{if(v==="logicaldesc"){var A=o(t[w]),y=o(s[w]);f.each((A.length<=y.length)?A:y,function(B,C){if(A[C]>y[C]){u=-1;return TAFFY.EXIT}else{if(A[C]<y[C]){u=1;return TAFFY.EXIT}}})}else{if(v==="asec"&&t[w]<s[w]){u=-1;return f.EXIT}else{if(v==="asec"&&t[w]>s[w]){u=1;return f.EXIT}else{if(v==="desc"&&t[w]>s[w]){u=-1;return f.EXIT}else{if(v==="desc"&&t[w]<s[w]){u=1;return f.EXIT}}}}}}if(u===0&&v==="logical"&&A.length<y.length){u=-1}else{if(u===0&&v==="logical"&&A.length>y.length){u=1}else{if(u===0&&v==="logicaldesc"&&A.length>y.length){u=-1}else{if(u===0&&v==="logicaldesc"&&A.length<y.length){u=1}}}}if(u!=0){return f.EXIT}});return u};return(p&&p.push)?p.sort(r):p};(function(){var p={},q=0;o=function(r){if(q>n){p={};q=0}return p["_"+r]||(function(){var v=String(r),u=[],z="_",t="",s,w,y;for(s=0,w=v.length;s<w;s++){y=v.charCodeAt(s);if((y>=48&&y<=57)||y===46){if(t!=="n"){t="n";u.push(z.toLowerCase());z=""}z=z+v.charAt(s)}else{if(t!=="s"){t="s";u.push(parseFloat(z));z=""}z=z+v.charAt(s)}}u.push((t==="n")?parseFloat(z):z.toLowerCase());u.shift();p["_"+r]=u;q++;return u}())}}());var d=function(){this.context({results:this.getDBI().query(this.context())})};c.extend("filter",function(){var q=TAFFY.mergeObj(this.context(),{run:null}),p=[];l(q.q,function(r){p.push(r)});q.q=p;l(arguments,function(r){q.q.push(e(r));q.filterRaw.push(r)});return this.getroot(q)});c.extend("order",function(q){q=q.split(",");var p=[],r;l(q,function(s){p.push(s.replace(/^\s*/,"").replace(/\s*$/,""))});r=TAFFY.mergeObj(this.context(),{sort:null});r.order=p;return this.getroot(r)});c.extend("limit",function(r){var q=TAFFY.mergeObj(this.context(),{});q.limit=r;if(q.run&&q.sort){var p=[];l(q.results,function(t,s){if((s+1)>r){return TAFFY.EXIT}p.push(t)});q.results=p}return this.getroot(q)});c.extend("start",function(r){var q=TAFFY.mergeObj(this.context(),{});q.start=r;if(q.run&&q.sort&&!q.limit){var p=[];l(q.results,function(t,s){if((s+1)>r){p.push(t)}});q.results=p}else{q=TAFFY.mergeObj(this.context(),{run:null,start:r})}return this.getroot(q)});c.extend("update",function(s,r,p){var t=true,v={},q=arguments,u;if(TAFFY.isString(s)&&(arguments.length===2||arguments.length===3)){v[s]=r;if(arguments.length===3){t=p}}else{v=s;if(q.length===2){t=r}}u=this;d.call(this);l(this.context().results,function(w){var x=v;if(TAFFY.isFunction(x)){x=x.apply(TAFFY.mergeObj(w,{}))}else{if(f.isFunction(x)){x=x(TAFFY.mergeObj(w,{}))}}if(TAFFY.isObject(x)){u.getDBI().update(w.___id,x,t)}});if(this.context().results.length){this.context({run:null})}return this});c.extend("remove",function(p){var q=this;var r=0;d.call(this);l(this.context().results,function(s){q.getDBI().remove(s.___id);r++});if(this.context().results.length){this.context({run:null});q.getDBI().removeCommit(p)}return r});c.extend("count",function(){d.call(this);return this.context().results.length});c.extend("callback",function(r,p){if(r){var q=this;setTimeout(function(){d.call(q);r.call(q.getroot(q.context()))},p||0)}return null});c.extend("get",function(){d.call(this);return this.context().results});c.extend("stringify",function(){return JSON.stringify(this.get())});c.extend("first",function(){d.call(this);return this.context().results[0]||false});c.extend("last",function(){d.call(this);return this.context().results[this.context().results.length-1]||false});c.extend("sum",function(){var q=0;d.call(this);var p=this;l(arguments,function(r){l(p.context().results,function(s){q=q+s[r]})});return q});c.extend("min",function(q){var p=null;d.call(this);l(this.context().results,function(s){if(p===null||s[q]<p){p=s[q]}});return p});(function(){var p=(function(){var s,q,r;s=function(w,y,v){var u,x,z,t;if(v.length===2){u=w[v[0]];z="===";x=y[v[1]]}else{u=w[v[0]];z=v[1];x=y[v[2]]}switch(z){case"===":return u===x;case"!==":return u!==x;case"<":return u<x;case">":return u>x;case"<=":return u<=x;case">=":return u>=x;case"==":return u==x;case"!=":return u!=x;default:throw String(z)+" is not supported"}};q=function(u,x){var t={},v,w;for(v in u){if(u.hasOwnProperty(v)){t[v]=u[v]}}for(v in x){if(x.hasOwnProperty(v)&&v!=="___id"&&v!=="___s"){w=!TAFFY.isUndefined(t[v])?"right_":"";t[w+String(v)]=x[v]}}return t};r=function(x){var t,v,u=arguments,w=u.length,y=[];if(typeof x.filter!=="function"){if(x.TAFFY){t=x()}else{throw"TAFFY DB or result not supplied"}}else{t=x}this.context({results:this.getDBI().query(this.context())});TAFFY.each(this.context().results,function(z){t.each(function(C){var A,B=true;CONDITION:for(v=1;v<w;v++){A=u[v];if(typeof A==="function"){B=A(z,C)}else{if(typeof A==="object"&&A.length){B=s(z,C,A)}else{B=false}}if(!B){break CONDITION}}if(B){y.push(q(z,C))}})});return TAFFY(y)()};return r}());c.extend("join",p)}());c.extend("max",function(q){var p=null;d.call(this);l(this.context().results,function(s){if(p===null||s[q]>p){p=s[q]}});return p});c.extend("select",function(){var q=[];var p=arguments;d.call(this);if(arguments.length===1){l(this.context().results,function(s){q.push(s[p[0]])})}else{l(this.context().results,function(s){var t=[];l(p,function(r){t.push(s[r])});q.push(t)})}return q});c.extend("distinct",function(){var q=[];var p=arguments;d.call(this);if(arguments.length===1){l(this.context().results,function(t){var s=t[p[0]];var u=false;l(q,function(r){if(s===r){u=true;return TAFFY.EXIT}});if(!u){q.push(s)}})}else{l(this.context().results,function(s){var u=[];l(p,function(r){u.push(s[r])});var t=false;l(q,function(v){var r=true;l(p,function(x,w){if(u[w]!==v[w]){r=false;return TAFFY.EXIT}});if(r){t=true;return TAFFY.EXIT}});if(!t){q.push(u)}})}return q});c.extend("supplant",function(q,p){var r=[];d.call(this);l(this.context().results,function(s){r.push(q.replace(/\{([^\{\}]*)\}/g,function(u,t){var w=s[t];return typeof w==="string"||typeof w==="number"?w:u}))});return(!p)?r.join(""):r});c.extend("each",function(p){d.call(this);l(this.context().results,p);return this});c.extend("map",function(p){var q=[];d.call(this);l(this.context().results,function(s){q.push(p(s))});return q});var f=function(x){var u=[],y={},v=1,r={template:false,onInsert:false,onUpdate:false,onRemove:false,onDBChange:false,storageName:false,forcePropertyCase:null,cacheSize:100,name:""},t=new Date(),s=0,q=0,A={},w,p,z;p=function(D){if(D.length===0){return u}var C=[];var B=false;l(D,function(E){if(f.isString(E)&&/[t][0-9]*[r][0-9]*/i.test(E)&&u[y[E]]){C.push(u[y[E]]);B=true}if(f.isObject(E)&&E.___id&&E.___s&&u[y[E.___id]]){C.push(u[y[E.___id]]);B=true}if(f.isArray(E)){l(E,function(F){l(p(F),function(G){C.push(G)})})}});if(B&&C.length>1){C=[]}return C};w={dm:function(B){if(B){t=B;A={};s=0;q=0}if(r.onDBChange){setTimeout(function(){r.onDBChange.call(u)},0)}if(r.storageName){setTimeout(function(){localStorage.setItem("taffy_"+r.storageName,JSON.stringify(u))})}return t},insert:function(E,F){var D=[],C=[],B=i(E);l(B,function(H,I){if(f.isArray(H)&&I===0){l(H,function(K){D.push((r.forcePropertyCase==="lower")?K.toLowerCase():(r.forcePropertyCase==="upper")?K.toUpperCase():K)});return true}else{if(f.isArray(H)){var G={};l(H,function(L,K){G[D[K]]=L});H=G}else{if(f.isObject(H)&&r.forcePropertyCase){var J={};b(H,function(L,K){J[(r.forcePropertyCase==="lower")?K.toLowerCase():(r.forcePropertyCase==="upper")?K.toUpperCase():K]=H[K]});H=J}}}v++;H.___id="T"+String(a+m).slice(-6)+"R"+String(a+v).slice(-6);H.___s=true;C.push(H.___id);if(r.template){H=f.mergeObj(r.template,H)}u.push(H);y[H.___id]=u.length-1;if(r.onInsert&&(F||TAFFY.isUndefined(F))){r.onInsert.call(H)}w.dm(new Date())});return z(C)},sort:function(B){u=k(u,B.split(","));y={};l(u,function(D,C){y[D.___id]=C});w.dm(new Date());return true},update:function(I,E,D){var H={};if(r.forcePropertyCase){b(E,function(J,K){H[(r.forcePropertyCase==="lower")?K.toLowerCase():(r.forcePropertyCase==="upper")?K.toUpperCase():K]=J});E=H}var G=u[y[I]];var F=f.mergeObj(G,E);var B={};var C=false;b(F,function(J,K){if(TAFFY.isUndefined(G[K])||G[K]!==J){B[K]=J;C=true}});if(C){if(r.onUpdate&&(D||TAFFY.isUndefined(D))){r.onUpdate.call(F,u[y[I]],B)}u[y[I]]=F;w.dm(new Date())}},remove:function(B){u[y[B]].___s=false},removeCommit:function(C){var B;for(B=u.length-1;B>-1;B--){if(!u[B].___s){if(r.onRemove&&(C||TAFFY.isUndefined(C))){r.onRemove.call(u[B])}y[u[B].___id]=undefined;u.splice(B,1)}}y={};l(u,function(E,D){y[E.___id]=D});w.dm(new Date())},query:function(C){var F,G;if(r.cacheSize){G="";l(C.filterRaw,function(H){if(f.isFunction(H)){G="nocache";return TAFFY.EXIT}});if(G===""){G=JSON.stringify(f.mergeObj(C,{q:false,run:false,sort:false}))}}if(!C.results||!C.run||(C.run&&w.dm()>C.run)){var B=[];if(r.cacheSize&&A[G]){A[G].i=s++;return A[G].results}else{if(C.q.length===0&&C.index.length===0){l(u,function(H){B.push(H)});F=B}else{var E=p(C.index);l(E,function(H){if(C.q.length===0||g(H,C.q)){B.push(H)}});F=B}}}else{F=C.results}if(C.order.length>0&&(!C.run||!C.sort)){F=k(F,C.order)}if(F.length&&((C.limit&&C.limit<F.length)||C.start)){var D=[];l(F,function(J,I){if(!C.start||(C.start&&(I+1)>=C.start)){if(C.limit){var H=(C.start)?(I+1)-C.start:I;if(H<C.limit){D.push(J)}else{if(H>C.limit){return TAFFY.EXIT}}}else{D.push(J)}}});F=D}if(r.cacheSize&&G!=="nocache"){q++;setTimeout(function(){if(q>=r.cacheSize*2){q=0;var H=s-r.cacheSize;var I={};b(function(K,J){if(K.i>=H){I[J]=K}});A=I}},0);A[G]={i:s++,results:F}}return F}};z=function(){var C,B;C=TAFFY.mergeObj(TAFFY.mergeObj(c,{insert:undefined}),{getDBI:function(){return w},getroot:function(D){return z.call(D)},context:function(D){if(D){B=TAFFY.mergeObj(B,D.hasOwnProperty("results")?TAFFY.mergeObj(D,{run:new Date(),sort:new Date()}):D)}return B},extend:undefined});B=(this&&this.q)?this:{limit:false,start:false,q:[],filterRaw:[],index:[],order:[],results:false,run:null,sort:null,settings:r};l(arguments,function(D){if(h(D)){B.index.push(D)}else{B.q.push(e(D))}B.filterRaw.push(D)});return C};m++;if(x){w.insert(x)}z.insert=w.insert;z.merge=function(E,D,F){var C={},B=[];F=F||false;D=D||"id";l(E,function(I){C[D]=I[D];B.push(I[D]);var H=z(C).first();if(H){w.update(H.___id,I,F)}else{w.insert(I,F)}});var G={};G[D]=B;return z(G)};z.TAFFY=true;z.sort=w.sort;z.settings=function(B){if(B){r=TAFFY.mergeObj(r,B);if(B.template){z().update(B.template)}}return r};z.store=function(D){var C=false;if(localStorage){if(D){var B=localStorage.getItem("taffy_"+D);if(B&&B.length>0){z.insert(B);C=true}if(u.length>0){setTimeout(function(){localStorage.setItem("taffy_"+r.storageName,JSON.stringify(u))})}}z.settings({storageName:D})}return z};return z};TAFFY=f;f.each=l;f.eachin=b;f.extend=c.extend;TAFFY.EXIT="TAFFYEXIT";TAFFY.mergeObj=function(r,p){var q={};b(r,function(s,t){q[t]=r[t]});b(p,function(s,t){q[t]=p[t]});return q};TAFFY.has=function(r,q){var p=true,s;if((r.TAFFY)){p=r(q);if(p.length>0){return true}else{return false}}else{switch(f.typeOf(r)){case"object":if(f.isObject(q)){b(q,function(t,u){if(p===true&&!f.isUndefined(r[u])&&r.hasOwnProperty(u)){p=f.has(r[u],q[u])}else{p=false;return TAFFY.EXIT}})}else{if(f.isArray(q)){l(q,function(t,u){p=f.has(r,q[u]);if(p){return TAFFY.EXIT}})}else{if(f.isString(q)){if(!TAFFY.isUndefined(r[q])){return true}else{return false}}}}return p;case"array":if(f.isObject(q)){l(r,function(t,u){p=f.has(r[u],q);if(p===true){return TAFFY.EXIT}})}else{if(f.isArray(q)){l(q,function(u,t){l(r,function(w,v){p=f.has(r[v],q[t]);if(p===true){return TAFFY.EXIT}});if(p===true){return TAFFY.EXIT}})}else{if(f.isString(q)||f.isNumber(q)){for(s=0;s<r.length;s++){p=f.has(r[s],q);if(p){return true}}}}}return p;case"string":if(f.isString(q)&&q===r){return true}break;default:if(f.typeOf(r)===f.typeOf(q)&&r===q){return true}break}}return false};TAFFY.hasAll=function(s,r){var q=TAFFY;if(q.isArray(r)){var p=true;l(r,function(t){p=q.has(s,t);if(p===false){return TAFFY.EXIT}});return p}else{return q.has(s,r)}};TAFFY.typeOf=function(p){var q=typeof p;if(q==="object"){if(p){if(typeof p.length==="number"&&!(p.propertyIsEnumerable("length"))){q="array"}}else{q="null"}}return q};TAFFY.getObjectKeys=function(p){var q=[];b(p,function(s,r){q.push(r)});q.sort();return q};TAFFY.isSameArray=function(q,p){return(TAFFY.isArray(q)&&TAFFY.isArray(p)&&q.join(",")===p.join(","))?true:false};TAFFY.isSameObject=function(s,q){var p=TAFFY,r=true;if(p.isObject(s)&&p.isObject(q)){if(p.isSameArray(p.getObjectKeys(s),p.getObjectKeys(q))){b(s,function(t,u){if(!((p.isObject(s[u])&&p.isObject(q[u])&&p.isSameObject(s[u],q[u]))||(p.isArray(s[u])&&p.isArray(q[u])&&p.isSameArray(s[u],q[u]))||(s[u]===q[u]))){r=false;return TAFFY.EXIT}})}else{r=false}}else{r=false}return r};(function(p){var q;for(q=0;q<p.length;q++){(function(r){TAFFY["is"+r]=function(s){return TAFFY.typeOf(s)===r.toLowerCase()?true:false}}(p[q]))}}(["String","Number","Object","Array","Boolean","Null","Function","Undefined"]))}}());if(typeof(exports)==="object"){exports.taffy=TAFFY};
View
84 taffy-test.html
@@ -0,0 +1,84 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+ <title>taffy test</title>
+
+ <script src="./taffy.js"></script>
+
+ <script>
+ // recursive object compare, for future use
+ Object.prototype.equals = function (x) {
+ var p;
+ for(p in this) {
+ if(typeof(x[p])=='undefined') {return false;}
+ }
+
+ for(p in this) {
+ if (this[p]) {
+ switch(typeof(this[p])) {
+ case 'object':
+ if (! this[p].equals(x[p])) { return false; }
+ break;
+ case 'function':
+ if (typeof(x[p])=='undefined' ||
+ (p != 'equals' && this[p].toString() != x[p].toString())
+ ){ return false; }
+ break;
+ default:
+ if (this[p] != x[p]) { return false; }
+ }
+ }
+ else {
+ if (x[p]){ return false; }
+ }
+ }
+
+ for(p in x) {
+ if(typeof(this[p])=='undefined') {return false;}
+ }
+
+ return true;
+ };
+
+
+
+ var key_name, data_val, friends_table, taffy_map;
+ friends_table = TAFFY([
+ {"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","status":"Active"},
+ {"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"},
+ {"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"},
+ {"id":4,"gender":"F","first":"Jennifer","last":"Gill","city":"Seattle, WA","status":"Active"}
+ ]);
+
+ taffy_map = {
+ t_by_city : friends_table({city:"Seattle, WA"}),
+ t_by_id : friends_table({id:1}),
+ t_by_id_f : friends_table({id:'1'}),
+ t_by_name : friends_table({first:'John',last:'Smith'}),
+ kelly_by_id : friends_table({id:2}).first(),
+ kelly_last_name : friends_table({id:2}).first().last,
+ id_list : friends_table().select('id'),
+ city_list : friends_table().distinct('city'),
+ };
+
+ for ( key_name in taffy_map ){
+ if ( taffy_map.hasOwnProperty(key_name) ){
+ data_val = taffy_map[key_name];
+ console.warn(key_name, data_val);
+ if ( data_val.hasOwnProperty('get') ){
+ console.warn(JSON.stringify(data_val.get()));
+ }
+ console.warn('----------------');
+ }
+ }
+ </script>
+</head>
+<body>
+<div>
+Please open your javascript console to see test results
+</div>
+</body>
+</html>
+
+
View
692 taffy.js
@@ -18,43 +18,34 @@
/*jslint browser : true, continue : true,
devel : true, indent : 2, maxerr : 500,
newcap : true, nomen : true, plusplus : true,
- regexp : true, sloppy : true, vars : true,
+ regexp : true, sloppy : true, vars : false,
white : true
- */
-/*global TAFFY, T */
+*/
// BUILD 193d48d, modified by mmikowski to pass jslint
-// Setup TAFFY Function (nameSpace) to return an object with methods
-var TAFFY, exports;
+// Setup TAFFY name space to return an object with methods
+var TAFFY, exports, T;
(function () {
'use strict';
+ var
+ typeList, makeTest, idx, typeKey,
+ version, TC, idpad, cmax,
+ API, protectJSON, each, eachin,
+ isIndexable, returnFilter, runFilters,
+ numcharsplit, orderByCol, run
+ ;
+
+
if ( ! TAFFY ){
// TC = Counter for Taffy DBs on page, used for unique IDs
// cmax = size of charnumarray conversion cache
// idpad = zeros to pad record IDs with
- var
- version = '2.6.1',
- TC = 1,
- idpad = '000000',
- cmax = 1000,
- API = {},
- protectJSON, each, eachin, isIndexable, returnFilter,
- runFilters, numcharsplit, orderByCol
- ;
-
- // 2012-07-24 mmikowski - UNTESTED
- // fix to fail-over to jQuery JSON support if native JSON object not available
- if ( ! window.JSON ){
- if ( ! $.toJSON ){
- throw 'This environment does not support the native JSON object.'
- + 'Please install the jQuery JSON plugin and we will use that.'
- ;
- }
- window.JSON = {};
- window.JSON.stringfy = $.toJSON;
- window.JSON.parse = $.secureEvalJSON;
- }
+ version = '2.6.2'; // proposed mmikowski 2012-08-06
+ TC = 1;
+ idpad = '000000';
+ cmax = 1000;
+ API = {};
protectJSON = function ( t ) {
// ****************************************
@@ -138,6 +129,7 @@ var TAFFY, exports;
};
isIndexable = function ( f ) {
+ var i;
// Check to see if record ID
if ( T.isString( f ) && /[t][0-9]*[r][0-9]*/i.test( f ) ){
return true;
@@ -149,7 +141,7 @@ var TAFFY, exports;
// Check to see if array of indexes
if ( T.isArray( f ) ){
- var i = true;
+ i = true;
each( f, function ( r ) {
if ( !isIndexable( r ) ){
i = false;
@@ -227,8 +219,7 @@ var TAFFY, exports;
// now build a func to loop over the filters and return true if ANY of the filters match
// This handles logical OR expressions
f = function () {
- var that = this;
- var match = false;
+ var that = this, match = false;
each( nf, function ( f ) {
if ( runFilters( that, f ) ){
match = true;
@@ -254,13 +245,13 @@ var TAFFY, exports;
'is' : v
};
}
- // loop over each value on the value object (if any)
+ // loop over each value on the value object - if any
eachin( v, function ( mtest, s ) {
- // s = match type (is, hasAll, like, etc)
- var c = [];
+ // s = match type, e.g. is, hasAll, like, etc
+ var c = [], looper;
// function to loop and apply filter
- var looper = (s === 'hasAll') ?
+ looper = (s === 'hasAll') ?
function ( mtest, func ) {
func( mtest );
} : each;
@@ -270,12 +261,11 @@ var TAFFY, exports;
// su = match success
// f = match false
- var su = true,
- f = false;
+ var su = true, f = false, matchFunc;
// push a function onto the filter collection to do the matching
- var matchFunc = function () {
+ matchFunc = function () {
// get the value from the record
var
@@ -300,6 +290,7 @@ var TAFFY, exports;
s = s.substring( 1, s.length );
}
// get the match results based on the s/match type
+ /*jslint eqeq : true */
r = (
(s === 'regex') ? (mtest.test( mvalue )) : (s === 'lt' || s === lt)
? (mvalue < mtest) : (s === 'gt' || s === gt)
@@ -339,6 +330,7 @@ var TAFFY, exports;
: (T[s] && T.isFunction( T[s] ))
? T[s]( mvalue, mtest ) : (false)
);
+ /*jslint eqeq : false */
r = (r && !su) ? false : (!r && !su) ? true : r;
return r;
@@ -355,8 +347,7 @@ var TAFFY, exports;
// else build a function to loop over all the filters and return true only if ALL match
// this is a logical AND
nf.push( function () {
- var that = this;
- var match = false;
+ var that = this, match = false;
each( c, function ( f ) {
if ( f.apply( that ) ){
match = true;
@@ -399,101 +390,112 @@ var TAFFY, exports;
return f;
}
};
-
- orderByCol = function (ar, o) {
- // ****************************************
- // *
- // * Takes: takes an array and a sort object
- // * Returns: the array sorted
- // * Purpose: Accept filters such as "[col], [col2]" or "[col] desc" and sort on those columns
- // ****************************************
-
- var sortFunc = function (a, b) {
- // function to pass to the native array.sort to sort an array
- var r = 0;
-
- T.each(o, function (sd) {
- // loop over the sort instructions
- // get the column name
- var o = sd.split(" ");
- var col = o[0];
-
- // get the direction
- var dir = (o.length === 1) ? "logical" : o[1];
-
-
- if (dir === 'logical') {
- // if dir is logical than grab the charnum arrays for the two values we are looking at
- var c = numcharsplit(a[col]),
- d = numcharsplit(b[col]);
- // loop over the charnumarrays until one value is higher than the other
- T.each((c.length <= d.length) ? c : d, function (x, i) {
- if (c[i] < d[i]) {
- r = -1;
-
- return TAFFY.EXIT
- } else if (c[i] > d[i]) {
- r = 1;
- return TAFFY.EXIT
- }
- })
- } else if (dir === 'logicaldesc') {
- // if logicaldesc than grab the charnum arrays for the two values we are looking at
- var c = numcharsplit(a[col]),
- d = numcharsplit(b[col]);
- // loop over the charnumarrays until one value is lower than the other
- T.each((c.length <= d.length) ? c : d, function (x, i) {
- if (c[i] > d[i]) {
- r = -1;
- return TAFFY.EXIT
- } else if (c[i] < d[i]) {
- r = 1;
- return TAFFY.EXIT
- }
- })
- } else if (dir === 'asec' && a[col] < b[col]) {
- // if asec (default) check to see which is higher
- r = -1;
- return T.EXIT;
- } else if (dir === 'asec' && a[col] > b[col]) {
- // if asec (default) check to see which is higher
- r = 1;
- return T.EXIT;
- } else if (dir === 'desc' && a[col] > b[col]) {
- // if desc check to see which is lower
- r = -1;
- return T.EXIT;
-
- } else if (dir === 'desc' && a[col] < b[col]) {
- // if desc check to see which is lower
- r = 1;
- return T.EXIT;
-
- }
- // if r is still 0 and we are doing a logical sort than look to see if one array is longer than the other
- if (r === 0 && dir === 'logical' && c.length < d.length) {
- r = -1;
- } else if (r === 0 && dir === 'logical' && c.length > d.length) {
- r = 1;
- } else if (r === 0 && dir === 'logicaldesc' && c.length > d.length) {
- r = -1;
- } else if (r === 0 && dir === 'logicaldesc' && c.length < d.length) {
- r = 1;
- }
-
- if (r != 0) {
- return T.EXIT
- }
-
-
- })
- return r;
- }
- // call the sort function and return the newly sorted array
- return (ar && ar.push) ? ar.sort(sortFunc) : ar;
-
-
- };
+
+ orderByCol = function ( ar, o ) {
+ // ****************************************
+ // *
+ // * Takes: takes an array and a sort object
+ // * Returns: the array sorted
+ // * Purpose: Accept filters such as "[col], [col2]" or "[col] desc" and sort on those columns
+ // *
+ // ****************************************
+
+ var sortFunc = function ( a, b ) {
+ // function to pass to the native array.sort to sort an array
+ var r = 0;
+
+ T.each( o, function ( sd ) {
+ // loop over the sort instructions
+ // get the column name
+ var o, col, dir, c, d;
+ o = sd.split( ' ' );
+ col = o[0];
+
+ // get the direction
+ dir = (o.length === 1) ? "logical" : o[1];
+
+
+ if ( dir === 'logical' ){
+ // if dir is logical than grab the charnum arrays for the two values we are looking at
+ c = numcharsplit( a[col] );
+ d = numcharsplit( b[col] );
+ // loop over the charnumarrays until one value is higher than the other
+ T.each( (c.length <= d.length) ? c : d, function ( x, i ) {
+ if ( c[i] < d[i] ){
+ r = -1;
+ return TAFFY.EXIT;
+ }
+ else if ( c[i] > d[i] ){
+ r = 1;
+ return TAFFY.EXIT;
+ }
+ } );
+ }
+ else if ( dir === 'logicaldesc' ){
+ // if logicaldesc than grab the charnum arrays for the two values we are looking at
+ c = numcharsplit( a[col] );
+ d = numcharsplit( b[col] );
+ // loop over the charnumarrays until one value is lower than the other
+ T.each( (c.length <= d.length) ? c : d, function ( x, i ) {
+ if ( c[i] > d[i] ){
+ r = -1;
+ return TAFFY.EXIT;
+ }
+ else if ( c[i] < d[i] ){
+ r = 1;
+ return TAFFY.EXIT;
+ }
+ } );
+ }
+ else if ( dir === 'asec' && a[col] < b[col] ){
+ // if asec - default - check to see which is higher
+ r = -1;
+ return T.EXIT;
+ }
+ else if ( dir === 'asec' && a[col] > b[col] ){
+ // if asec - default - check to see which is higher
+ r = 1;
+ return T.EXIT;
+ }
+ else if ( dir === 'desc' && a[col] > b[col] ){
+ // if desc check to see which is lower
+ r = -1;
+ return T.EXIT;
+
+ }
+ else if ( dir === 'desc' && a[col] < b[col] ){
+ // if desc check to see which is lower
+ r = 1;
+ return T.EXIT;
+
+ }
+ // if r is still 0 and we are doing a logical sort than look to see if one array is longer than the other
+ if ( r === 0 && dir === 'logical' && c.length < d.length ){
+ r = -1;
+ }
+ else if ( r === 0 && dir === 'logical' && c.length > d.length ){
+ r = 1;
+ }
+ else if ( r === 0 && dir === 'logicaldesc' && c.length > d.length ){
+ r = -1;
+ }
+ else if ( r === 0 && dir === 'logicaldesc' && c.length < d.length ){
+ r = 1;
+ }
+
+ if ( r !== 0 ){
+ return T.EXIT;
+ }
+
+
+ } );
+ return r;
+ };
+ // call the sort function and return the newly sorted array
+ return (ar && ar.push) ? ar.sort( sortFunc ) : ar;
+
+
+ };
// ****************************************
// *
@@ -565,7 +567,7 @@ var TAFFY, exports;
// ****************************************
- var run = function () {
+ run = function () {
this.context( {
results : this.getDBI().query( this.context() )
});
@@ -621,11 +623,14 @@ var TAFFY, exports;
// * Purpose: takes a limit number to limit the number of rows returned by a query. Will update the results
// * of a query
// ****************************************
- var nc = TAFFY.mergeObj( this.context(), {});
+ var nc = TAFFY.mergeObj( this.context(), {}),
+ limitedresults
+ ;
+
nc.limit = n;
if ( nc.run && nc.sort ){
- var limitedresults = [];
+ limitedresults = [];
each( nc.results, function ( i, x ) {
if ( (x + 1) > n ){
return TAFFY.EXIT;
@@ -644,11 +649,14 @@ var TAFFY, exports;
// * Purpose: takes a limit number to limit the number of rows returned by a query. Will update the results
// * of a query
// ****************************************
- var nc = TAFFY.mergeObj( this.context(), {} );
+ var nc = TAFFY.mergeObj( this.context(), {} ),
+ limitedresults
+ ;
+
nc.start = n;
if ( nc.run && nc.sort && !nc.limit ){
- var limitedresults = [];
+ limitedresults = [];
each( nc.results, function ( i, x ) {
if ( (x + 1) > n ){
limitedresults.push( i );
@@ -710,8 +718,7 @@ var TAFFY, exports;
// *
// * Purpose: removes records from the DB via the remove and removeCommit DBI methods
// ****************************************
- var that = this;
- var c = 0;
+ var that = this, c = 0;
run.call( this );
each( this.context().results, function ( r ) {
that.getDBI().remove( r.___id );
@@ -796,9 +803,8 @@ var TAFFY, exports;
// * Takes: column to sum up
// * Returns: Sums the values of a column
// ****************************************
- var total = 0;
- run.call( this );
- var that = this;
+ var total = 0, that = this;
+ run.call( that );
each( arguments, function ( c ) {
each( that.context().results, function ( r ) {
total = total + r[c];
@@ -822,167 +828,170 @@ var TAFFY, exports;
});
return lowest;
});
- /*
- Taffy innerJoin Extension (OCD edition)
-=======================================
-
-How to Use
-**********
-
-left_table.innerJoin( right_table, condition1 <,... conditionN> )
-
-A condition can take one of 2 forms:
-
- 1. An ARRAY with 2 or 3 values:
- A column name from the left table, an optional comparison string,
- and column name from the right table. The condition passes if the test
- indicated is true. If the condition string is omitted, '===' is assumed.
- EXAMPLES: [ 'last_used_time', '>=', 'current_use_time' ], [ 'user_id','id' ]
-
- 2. A FUNCTION:
- The function receives a left table row and right table row during the
- cartesian join. If the function returns true for the rows considered,
- the merged row is included in the result set.
- EXAMPLE: function (l,r){ return l.name === r.label; }
-
-Conditions are considered in the order they are presented. Therefore the best
-performance is realized when the least expensive and highest prune-rate
-conditions are placed first, since if they return false Taffy skips any
-further condition tests.
-
-Other notes
-***********
-
-This code passes jslint with the exception of 2 warnings about
-the '==' and '!=' lines. We can't do anything about that short of
-deleting the lines.
-
-Credits
-*******
-
-Heavily based upon the work of Ian Toltz.
-Revisions to API by Michael Mikowski.
-Code convention per standards in http://manning.com/mikowski
-
-*/
-
-/*jslint browser : true, continue : true,
- devel : true, indent : 2, maxerr : 50,
- newcap : true, plusplus : true, regexp : true,
- sloppy : true, vars : true, white : true
-*/
-
-/*global TAFFY */
-
-(function () {
- var innerJoinFunction = (function () {
- var fnCompareList, fnCombineRow, fnMain;
-
- fnCompareList = function ( left_row, right_row, arg_list ) {
- var data_lt, data_rt, op_code, error;
-
- if ( arg_list.length === 2 ){
- data_lt = left_row[arg_list[0]];
- op_code = '===';
- data_rt = right_row[arg_list[1]];
- }
- else {
- data_lt = left_row[arg_list[0]];
- op_code = arg_list[1];
- data_rt = right_row[arg_list[2]];
- }
- switch ( op_code ){
- case '===' : return data_lt === data_rt;
- case '!==' : return data_lt !== data_rt;
- case '<' : return data_lt < data_rt;
- case '>' : return data_lt > data_rt;
- case '<=' : return data_lt <= data_rt;
- case '>=' : return data_lt >= data_rt;
- case '==' : return data_lt == data_rt;
- case '!=' : return data_lt != data_rt;
- default :
- throw String(op_code) + ' is not supported';
- }
- };
+ // Taffy innerJoin Extension (OCD edition)
+ // =======================================
+ //
+ // How to Use
+ // **********
+ //
+ // left_table.innerJoin( right_table, condition1 <,... conditionN> )
+ //
+ // A condition can take one of 2 forms:
+ //
+ // 1. An ARRAY with 2 or 3 values:
+ // A column name from the left table, an optional comparison string,
+ // and column name from the right table. The condition passes if the test
+ // indicated is true. If the condition string is omitted, '===' is assumed.
+ // EXAMPLES: [ 'last_used_time', '>=', 'current_use_time' ], [ 'user_id','id' ]
+ //
+ // 2. A FUNCTION:
+ // The function receives a left table row and right table row during the
+ // cartesian join. If the function returns true for the rows considered,
+ // the merged row is included in the result set.
+ // EXAMPLE: function (l,r){ return l.name === r.label; }
+ //
+ // Conditions are considered in the order they are presented. Therefore the best
+ // performance is realized when the least expensive and highest prune-rate
+ // conditions are placed first, since if they return false Taffy skips any
+ // further condition tests.
+ //
+ // Other notes
+ // ***********
+ //
+ // This code passes jslint with the exception of 2 warnings about
+ // the '==' and '!=' lines. We can't do anything about that short of
+ // deleting the lines.
+ //
+ // Credits
+ // *******
+ //
+ // Heavily based upon the work of Ian Toltz.
+ // Revisions to API by Michael Mikowski.
+ // Code convention per standards in http://manning.com/mikowski
+ (function () {
+ var innerJoinFunction = (function () {
+ var fnCompareList, fnCombineRow, fnMain;
- fnCombineRow = function ( left_row, right_row ) {
- var out_map = {}, i, prefix;
+ fnCompareList = function ( left_row, right_row, arg_list ) {
+ var data_lt, data_rt, op_code, error;
- for ( i in left_row ){
- if ( left_row.hasOwnProperty(i)){
- out_map[i] = left_row[i];
- }
- }
- for (i in right_row) {
- if ( right_row.hasOwnProperty(i) && i !== '___id' && i !== '___s' ) {
- prefix = !TAFFY.isUndefined(out_map[i]) ? 'right_' : '';
- out_map[prefix + String(i) ] = right_row[i];
- }
- }
- return out_map;
- };
-
- fnMain = function ( table ) {
- var
- right_table, i,
- arg_list = arguments,
- arg_length = arg_list.length,
- result_list = []
- ;
+ if ( arg_list.length === 2 ){
+ data_lt = left_row[arg_list[0]];
+ op_code = '===';
+ data_rt = right_row[arg_list[1]];
+ }
+ else {
+ data_lt = left_row[arg_list[0]];
+ op_code = arg_list[1];
+ data_rt = right_row[arg_list[2]];
+ }
- if ( typeof table.filter !== 'function' ) {
- if ( table.TAFFY) { right_table = table(); }
- else {
- throw 'TAFFY DB or result not supplied';
- }
- }
- else { right_table = table; }
+ /*jslint eqeq : true */
+ switch ( op_code ){
+ case '===' :
+ return data_lt === data_rt;
+ case '!==' :
+ return data_lt !== data_rt;
+ case '<' :
+ return data_lt < data_rt;
+ case '>' :
+ return data_lt > data_rt;
+ case '<=' :
+ return data_lt <= data_rt;
+ case '>=' :
+ return data_lt >= data_rt;
+ case '==' :
+ return data_lt == data_rt;
+ case '!=' :
+ return data_lt != data_rt;
+ default :
+ throw String( op_code ) + ' is not supported';
+ }
+ // 'jslint eqeq : false' here results in
+ // "Unreachable '/*jslint' after 'return'".
+ // We don't need it though, as the rule exception
+ // is discarded at the end of this functional scope
+ };
- this.context({
- results: this.getDBI().query( this.context() )
- });
+ fnCombineRow = function ( left_row, right_row ) {
+ var out_map = {}, i, prefix;
- TAFFY.each(this.context().results, function ( left_row ){
- right_table.each( function ( right_row ) {
- var arg_data, is_ok = true;
- CONDITION:
- for (i = 1; i < arg_length; i++ ) {
- arg_data = arg_list[i];
- if (typeof arg_data === 'function'){
- is_ok = arg_data( left_row, right_row );
+ for ( i in left_row ){
+ if ( left_row.hasOwnProperty( i ) ){
+ out_map[i] = left_row[i];
}
- else if ( typeof arg_data === 'object' && arg_data.length ){
- is_ok = fnCompareList( left_row, right_row, arg_data );
+ }
+ for ( i in right_row ){
+ if ( right_row.hasOwnProperty( i ) && i !== '___id' &&
+ i !== '___s' )
+ {
+ prefix = !TAFFY.isUndefined( out_map[i] ) ? 'right_' : '';
+ out_map[prefix + String( i ) ] = right_row[i];
}
+ }
+ return out_map;
+ };
+
+ fnMain = function ( table ) {
+ var
+ right_table, i,
+ arg_list = arguments,
+ arg_length = arg_list.length,
+ result_list = []
+ ;
+
+ if ( typeof table.filter !== 'function' ){
+ if ( table.TAFFY ){ right_table = table(); }
else {
- is_ok = false;
+ throw 'TAFFY DB or result not supplied';
}
-
- if ( ! is_ok ) { break CONDITION; } // short circuit
}
+ else { right_table = table; }
+
+ this.context( {
+ results : this.getDBI().query( this.context() )
+ } );
+
+ TAFFY.each( this.context().results, function ( left_row ) {
+ right_table.each( function ( right_row ) {
+ var arg_data, is_ok = true;
+ CONDITION:
+ for ( i = 1; i < arg_length; i++ ){
+ arg_data = arg_list[i];
+ if ( typeof arg_data === 'function' ){
+ is_ok = arg_data( left_row, right_row );
+ }
+ else if ( typeof arg_data === 'object' && arg_data.length ){
+ is_ok = fnCompareList( left_row, right_row, arg_data );
+ }
+ else {
+ is_ok = false;
+ }
- if ( is_ok ){
- result_list.push( fnCombineRow(left_row, right_row ) );
- }
- });
- });
- return TAFFY(result_list)();
- };
+ if ( !is_ok ){ break CONDITION; } // short circuit
+ }
- return fnMain;
- }());
+ if ( is_ok ){
+ result_list.push( fnCombineRow( left_row, right_row ) );
+ }
+ } );
+ } );
+ return TAFFY( result_list )();
+ };
- API.extend('join', innerJoinFunction);
-}());
-
+ return fnMain;
+ }());
+
+ API.extend( 'join', innerJoinFunction );
+ }());
API.extend( 'max', function ( c ) {
// ****************************************
// *
// * Takes: column to find max
// * Returns: the highest value
- // ****************************************
+ // ****************************************
var highest = null;
run.call( this );
each( this.context().results, function ( r ) {
@@ -992,6 +1001,7 @@ Code convention per standards in http://manning.com/mikowski
});
return highest;
});
+
API.extend( 'select', function () {
// ****************************************
// *
@@ -1000,8 +1010,7 @@ Code convention per standards in http://manning.com/mikowski
// * Note if more than one column is given an array of arrays is returned
// ****************************************
- var ra = [];
- var args = arguments;
+ var ra = [], args = arguments;
run.call( this );
if ( arguments.length === 1 ){
@@ -1028,14 +1037,12 @@ Code convention per standards in http://manning.com/mikowski
// * Returns: array of values
// * Note if more than one column is given an array of arrays is returned
// ****************************************
- var ra = [];
- var args = arguments;
+ var ra = [], args = arguments;
run.call( this );
if ( arguments.length === 1 ){
each( this.context().results, function ( r ) {
- var v = r[args[0]];
- var dup = false;
+ var v = r[args[0]], dup = false;
each( ra, function ( d ) {
if ( v === d ){
dup = true;
@@ -1049,11 +1056,10 @@ Code convention per standards in http://manning.com/mikowski
}
else {
each( this.context().results, function ( r ) {
- var row = [];
+ var row = [], dup = false;
each( args, function ( c ) {
row.push( r[c] );
});
- var dup = false;
each( ra, function ( d ) {
var ldup = true;
each( args, function ( c, i ) {
@@ -1077,7 +1083,7 @@ Code convention per standards in http://manning.com/mikowski
API.extend( 'supplant', function ( template, returnarray ) {
// ****************************************
// *
- // * Takes: a string template formated with {key} to be replaced with values from the rows, flag to determine if we want array of strings
+ // * Takes: a string template formated with key to be replaced with values from the rows, flag to determine if we want array of strings
// * Returns: array of values or a string
// ****************************************
var ra = [];
@@ -1119,7 +1125,7 @@ Code convention per standards in http://manning.com/mikowski
- var T = function ( d ) {
+ T = function ( d ) {
// ****************************************
// *
// * T is the main TAFFY object
@@ -1138,7 +1144,7 @@ Code convention per standards in http://manning.com/mikowski
storageName : false,
forcePropertyCase : null,
cacheSize : 100,
- name : ""
+ name : ''
},
dm = new Date(),
CacheCount = 0,
@@ -1167,12 +1173,12 @@ Code convention per standards in http://manning.com/mikowski
// * Returns: collection with records matching indexed filters
// ****************************************
+ var records = [], UniqueEnforce = false;
+
if ( indexes.length === 0 ){
return TOb;
}
- var records = [];
- var UniqueEnforce = false;
each( indexes, function ( f ) {
// Check to see if record ID
if ( T.isString( f ) && /[t][0-9]*[r][0-9]*/i.test( f ) &&
@@ -1242,9 +1248,11 @@ Code convention per standards in http://manning.com/mikowski
// * Purpose: merge the object with the template, add an ID, insert into DB, call insert event
// ****************************************
var columns = [],
- records = [],
- input = protectJSON( i );
+ records = [],
+ input = protectJSON( i )
+ ;
each( input, function ( v, i ) {
+ var nv, o;
if ( T.isArray( v ) && i === 0 ){
each( v, function ( av ) {
@@ -1256,15 +1264,15 @@ Code convention per standards in http://manning.com/mikowski
return true;
}
else if ( T.isArray( v ) ){
- var nv = {};
+ nv = {};
each( v, function ( av, ai ) {
nv[columns[ai]] = av;
});
v = nv;
}
else if ( T.isObject( v ) && settings.forcePropertyCase ){
- var o = {};
+ o = {};
eachin( v, function ( av, ai ) {
o[(settings.forcePropertyCase === 'lower') ? ai.toLowerCase()
@@ -1314,7 +1322,7 @@ Code convention per standards in http://manning.com/mikowski
// * Purpose: Update a record and change some or all values, call the on update method
// ****************************************
- var nc = {};
+ var nc = {}, or, nr, tc, hasChange;
if ( settings.forcePropertyCase ){
eachin( changes, function ( v, p ) {
nc[(settings.forcePropertyCase === 'lower') ? p.toLowerCase()
@@ -1324,11 +1332,11 @@ Code convention per standards in http://manning.com/mikowski
changes = nc;
}
- var or = TOb[ID[id]];
- var nr = T.mergeObj( or, changes );
+ or = TOb[ID[id]];
+ nr = T.mergeObj( or, changes );
- var tc = {};
- var hasChange = false;
+ tc = {};
+ hasChange = false;
eachin( nr, function ( v, i ) {
if ( TAFFY.isUndefined( or[i] ) || or[i] !== v ){
tc[i] = v;
@@ -1383,7 +1391,7 @@ Code convention per standards in http://manning.com/mikowski
// *
// * Takes: the context object for a query and either returns a cache result or a new query result
// ****************************************
- var returnq, cid;
+ var returnq, cid, results, indexed, limitq, ni;
if ( settings.cacheSize ) {
cid = '';
@@ -1402,7 +1410,7 @@ Code convention per standards in http://manning.com/mikowski
if ( !context.results || !context.run ||
(context.run && DBI.dm() > context.run) )
{
- var results = [];
+ results = [];
// check Cache
@@ -1422,7 +1430,7 @@ Code convention per standards in http://manning.com/mikowski
else {
// use indexes
- var indexed = runIndexes( context.index );
+ indexed = runIndexes( context.index );
// run filters
each( indexed, function ( r ) {
@@ -1453,13 +1461,13 @@ Code convention per standards in http://manning.com/mikowski
((context.limit && context.limit < returnq.length) ||
context.start)
) {
- var limitq = [];
+ limitq = [];
each( returnq, function ( r, i ) {
if ( !context.start ||
(context.start && (i + 1) >= context.start) )
{
if ( context.limit ){
- var ni = (context.start) ? (i + 1) - context.start : i;
+ ni = (context.start) ? (i + 1) - context.start : i;
if ( ni < context.limit ){
limitq.push( r );
}
@@ -1480,10 +1488,11 @@ Code convention per standards in http://manning.com/mikowski
CacheClear++;
setTimeout( function () {
+ var bCounter, nc;
if ( CacheClear >= settings.cacheSize * 2 ){
CacheClear = 0;
- var bCounter = CacheCount - settings.cacheSize;
- var nc = {};
+ bCounter = CacheCount - settings.cacheSize;
+ nc = {};
eachin( function ( r, k ) {
if ( r.i >= bCounter ){
nc[k] = r;
@@ -1509,8 +1518,8 @@ Code convention per standards in http://manning.com/mikowski
// ****************************************
// ****************************************
// *
- // * iAPI is the the method collection valiable when a query has been started by calling dbname()
- // * Certain methods are or are not avaliable once you have started a query such as insert (you can only insert into root)
+ // * iAPI is the the method collection valiable when a query has been started by calling dbname
+ // * Certain methods are or are not avaliable once you have started a query such as insert -- you can only insert into root
// ****************************************
iAPI = TAFFY.mergeObj( TAFFY.mergeObj( API, { insert : undefined } ),
{ getDBI : function () { return DBI; },
@@ -1578,24 +1587,26 @@ Code convention per standards in http://manning.com/mikowski
root.merge = function ( i, key, runEvent ) {
var
search = {},
- finalSearch = []
+ finalSearch = [],
+ obj = {}
;
runEvent = runEvent || false;
key = key || 'id';
each( i, function ( o ) {
+ var existingObject;
search[key] = o[key];
finalSearch.push( o[key] );
- var existingObject = root( search ).first();
+ existingObject = root( search ).first();
if ( existingObject ){
DBI.update( existingObject.___id, o, runEvent );
}
else {
DBI.insert( o, runEvent );
}
});
- var obj = {};
+
obj[key] = finalSearch;
return root( obj );
};
@@ -1604,7 +1615,7 @@ Code convention per standards in http://manning.com/mikowski
root.sort = DBI.sort;
// ****************************************
// *
- // * These are the methods that can be accessed on off the root DB function. Example dbname.insert();
+ // * These are the methods that can be accessed on off the root DB function. Example dbname.insert;
// ****************************************
root.settings = function ( n ) {
// ****************************************
@@ -1623,18 +1634,18 @@ Code convention per standards in http://manning.com/mikowski
// ****************************************
// *
- // * These are the methods that can be accessed on off the root DB function. Example dbname.insert();
+ // * These are the methods that can be accessed on off the root DB function. Example dbname.insert;
// ****************************************
root.store = function ( n ) {
// ****************************************
// *
// * Setup localstorage for this DB on a given name
// * Pull data into the DB as needed
// ****************************************
- var r = false;
+ var r = false, i;
if ( localStorage ){
if ( n ){
- var i = localStorage.getItem( 'taffy_' + n );
+ i = localStorage.getItem( 'taffy_' + n );
if ( i && i.length > 0 ){
root.insert( i );
r = true;
@@ -1824,9 +1835,9 @@ Code convention per standards in http://manning.com/mikowski
// ****************************************
TAFFY.hasAll = function ( var1, var2 ) {
- var T = TAFFY;
+ var T = TAFFY, ar;
if ( T.isArray( var2 ) ){
- var ar = true;
+ ar = true;
each( var2, function ( v ) {
ar = T.has( var1, v );
if ( ar === false ){
@@ -1933,21 +1944,26 @@ Code convention per standards in http://manning.com/mikowski
// * Return true if obj is datatype, false otherwise
// * Purpose: Used to determine if arguments are of certain data type
// *
+ // * mmikowski 2012-08-06 refactored to make much less "magical":
+ // * fewer closures and passes jslint
+ // *
// ****************************************
- (function ( ts ) {
- var z;
- for ( z = 0; z < ts.length; z++ ){
- (function ( y ) {
- TAFFY['is' + y] = function ( c ) {
- return TAFFY.typeOf( c ) === y.toLowerCase() ? true : false;
- };
- }( ts[z] ));
- }
- }( ['String', 'Number', 'Object', 'Array',
- 'Boolean', 'Null', 'Function', 'Undefined'
- ]));
-
+ typeList = [
+ 'String', 'Number', 'Object', 'Array',
+ 'Boolean', 'Null', 'Function', 'Undefined'
+ ];
+
+ makeTest = function ( thisKey ) {
+ return function ( data ) {
+ return TAFFY.typeOf( data ) === thisKey.toLowerCase() ? true : false;
+ };
+ };
+
+ for ( idx = 0; idx < typeList.length; idx++ ){
+ typeKey = typeList[idx];
+ TAFFY['is' + typeKey] = makeTest( typeKey );
+ }
}
}());

0 comments on commit 0287ffd

Please sign in to comment.