PageRenderTime 167ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/public/javascripts/jquery-tinysort-min.js

https://bitbucket.org/openfisma-ondemand/openfisma
JavaScript | 300 lines | 210 code | 10 blank | 80 comment | 39 complexity | 32179992e63d11eab820a75d3f1c94a1 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1, GPL-3.0, Apache-2.0, EPL-1.0
  1. /*
  2. * jQuery TinySort 1.3.27
  3. * A plugin to sort child nodes by (sub) contents or attributes.
  4. *
  5. * Copyright (c) 2008-2012 Ron Valstar http://www.sjeiti.com/
  6. *
  7. * Dual licensed under the MIT and GPL licenses:
  8. * http://www.opensource.org/licenses/mit-license.php
  9. * http://www.gnu.org/licenses/gpl.html
  10. *
  11. * contributors:
  12. * brian.gibson@gmail.com
  13. * michael.thornberry@gmail.com
  14. *
  15. * Usage:
  16. * $("ul#people>li").tsort();
  17. * $("ul#people>li").tsort("span.surname");
  18. * $("ul#people>li").tsort("span.surname",{order:"desc"});
  19. * $("ul#people>li").tsort({place:"end"});
  20. *
  21. * Change default like so:
  22. * $.tinysort.defaults.order = "desc";
  23. *
  24. * in this update:
  25. * - replaced pushStack with actual replace so initial jQ object is reordered (not only the returned object)
  26. * - fixed non-latin character ordering
  27. *
  28. * in last update:
  29. * - removed isNum
  30. * - fixed mixed literal/numeral values
  31. * - refactored fn contains()
  32. * - revision number now corresponds to svn revision
  33. *
  34. * Todos:
  35. * - todo: uppercase vs lowercase
  36. * - todo: 'foobar' != 'foobars' in non-latin
  37. *
  38. */
  39. ;(function($) {
  40. // private vars
  41. var fls = !1 // minify placeholder
  42. ,nll = null // minify placeholder
  43. ,prsflt = parseFloat // minify placeholder
  44. ,frCrCd = String.fromCharCode // minify placeholder
  45. ,mathmn = Math.min // minify placeholder
  46. ,rxLastNr = /(-?\d+\.?\d*)$/g // regex for testing strings ending on numbers
  47. //
  48. // character specific ordering is off by default for speed
  49. ,sCharOrder // equals the input oSettings.charOrder so we can test any changes
  50. ,aAllChars = [] // all latin chars 32-255
  51. ,aOrderChar // similar to sAllChars but with the changed char order
  52. ,bDoubles // boolean indicating double-non-latin chars, ie: lj, dž, Aa, ch, ss etc...
  53. ,iReplace = 0x2500 // doubles are replaced with Unicode char starting at 0x2500
  54. ,oReplace = {} // replacement object
  55. ,rxNotLatin // regular expression to test for non-latin chars
  56. ;
  57. // create basic latin string chars 32-255
  58. for (var i=32,s=frCrCd(i),len=255;i<len;i++,s=frCrCd(i).toLowerCase()) { // using lowerCase instead of upperCase so _ will sort before
  59. if ($.inArray(s, aAllChars) < 0) {
  60. aAllChars.push(s);
  61. }
  62. }
  63. aAllChars.sort();
  64. //
  65. // init plugin
  66. $.tinysort = {
  67. id: 'TinySort'
  68. ,version: '1.3.27'
  69. ,copyright: 'Copyright (c) 2008-2012 Ron Valstar'
  70. ,uri: 'http://tinysort.sjeiti.com/'
  71. ,licenced: {
  72. MIT: 'http://www.opensource.org/licenses/mit-license.php'
  73. ,GPL: 'http://www.gnu.org/licenses/gpl.html'
  74. }
  75. ,defaults: { // default settings
  76. order: 'asc' // order: asc, desc or rand
  77. ,attr: nll // order by attribute value
  78. ,data: nll // use the data attribute for sorting
  79. ,useVal: fls // use element value instead of text
  80. ,place: 'start' // place ordered elements at position: start, end, org (original position), first
  81. ,returns: fls // return all elements or only the sorted ones (true/false)
  82. ,cases: fls // a case sensitive sort orders [aB,aa,ab,bb]
  83. ,forceStrings:fls // if false the string '2' will sort with the value 2, not the string '2'
  84. ,sortFunction: nll // override the default sort function
  85. ,charOrder: sCharOrder // the order of non-latin characters
  86. }
  87. };
  88. $.fn.extend({
  89. tinysort: function(_find,_settings) {
  90. if (_find&&typeof(_find)!='string') {
  91. _settings = _find;
  92. _find = nll;
  93. }
  94. var oSettings = $.extend({}, $.tinysort.defaults, _settings)
  95. ,sParent
  96. ,oThis = this
  97. ,iLen = $(this).length
  98. ,oElements = {} // contains sortable- and non-sortable list per parent
  99. ,bFind = !(!_find||_find=='')
  100. ,bAttr = !(oSettings.attr===nll||oSettings.attr=="")
  101. ,bData = oSettings.data!==nll
  102. // since jQuery's filter within each works on array index and not actual index we have to create the filter in advance
  103. ,bFilter = bFind&&_find[0]==':'
  104. ,$Filter = bFilter?oThis.filter(_find):oThis
  105. ,fnSort = oSettings.sortFunction
  106. ,iAsc = oSettings.order=='asc'?1:-1
  107. ,aNewOrder = [];
  108. // check charOrder (non latin chars)
  109. // sCharOrder only to check wether other vars are set
  110. // variables used on sort
  111. // - oSettings.charOrder to test
  112. // - bDoubles to test
  113. // - oReplace for doubles
  114. // - rxNotLatin to test
  115. // - aOrderChar to order
  116. //
  117. if (oSettings.charOrder!=sCharOrder) {
  118. sCharOrder = oSettings.charOrder;
  119. if (!oSettings.charOrder) {
  120. bDoubles = false;
  121. iReplace = 0x2500;
  122. oReplace = {};
  123. rxNotLatin = aOrderChar = nll;
  124. } else {
  125. aOrderChar = aAllChars.slice(0); // first set to entire 32-255 charlist
  126. bDoubles = false;
  127. // then loop through the sCharOrder rule
  128. for (var
  129. aCharNotLatin = []
  130. ,fnAddNonLatinChar = function(key,nonLatin){
  131. aCharNotLatin.push(nonLatin);
  132. oReplace[oSettings.cases?key:key.toLowerCase()] = nonLatin;
  133. }
  134. ,sAllCharNotLatin = ''
  135. ,sCharLatin = 'z' // if oSettings.charOrder has no [a-z] characters are appended to z
  136. ,l = sCharOrder.length
  137. ,j,m // init
  138. ,i=0;i<l;i++) { // loop through chars to set 'rxNotLatin' and 'sOrderChar'
  139. var sChar = sCharOrder[i]
  140. ,iChar = sChar.charCodeAt()
  141. ,bIsLatin = iChar>96&&iChar<123; // 'a'.charCodeAt()===97 'z'.charCodeAt()===122
  142. if (!bIsLatin){
  143. if (sChar=='[') { // find replace chars: ë will sort similar to e
  144. var iCharNotLatin = aCharNotLatin.length
  145. ,sLastChar = iCharNotLatin?aCharNotLatin[iCharNotLatin-1]:sCharLatin
  146. ,sReplaces = sCharOrder.substr(i+1).match(/[^\]]*/)[0]
  147. ,aDoubles = sReplaces.match(/{[^}]*}/g); // find doubles: dž, ss, lj ...
  148. if (aDoubles) {
  149. for (j=0,m=aDoubles.length;j<m;j++) {
  150. var sCode = aDoubles[j];
  151. i += sCode.length; // increment i because of .replace(...
  152. sReplaces = sReplaces.replace(sCode,'');
  153. fnAddNonLatinChar(sCode.replace(/[{}]/g,''),sLastChar);
  154. bDoubles = true;
  155. }
  156. }
  157. for (j=0,m=sReplaces.length;j<m;j++) fnAddNonLatinChar(sLastChar,sReplaces[j]);
  158. i += sReplaces.length+1;
  159. } else if (sChar=='{') { // find doubles: dž, ss, lj ...
  160. var sDouble = sCharOrder.substr(i+1).match(/[^}]*/)[0];
  161. fnAddNonLatinChar(sDouble,frCrCd(iReplace++)); // replace the double with single Unicode 0x2500+
  162. i += sDouble.length+1;
  163. bDoubles = true;
  164. } else {
  165. aCharNotLatin.push(sChar);
  166. }
  167. }
  168. if (aCharNotLatin.length&&(bIsLatin||i===l-1)) {
  169. var sCharNotLatin = aCharNotLatin.join('');
  170. sAllCharNotLatin += sCharNotLatin;
  171. // first remove non latin chars
  172. $.each(sCharNotLatin,function(j,s){
  173. aOrderChar.splice(aOrderChar.indexOf(s),1);
  174. });
  175. // then append chars to latin char
  176. var aParse = aCharNotLatin.slice(0);
  177. aParse.splice(0,0,aOrderChar.indexOf(sCharLatin)+1,0);
  178. Array.prototype.splice.apply(aOrderChar,aParse);
  179. //
  180. aCharNotLatin.length = 0;
  181. }
  182. if (i+1===l) rxNotLatin = new RegExp('['+sAllCharNotLatin+']','gi'); // make regex to test for chars
  183. else if (bIsLatin) sCharLatin = sChar;
  184. }
  185. }
  186. }
  187. if (!fnSort) fnSort = oSettings.order=='rand'?function() {
  188. return Math.random()<.5?1:-1;
  189. }:function(a,b) {
  190. var bNumeric = fls
  191. // maybe toLower
  192. ,sA = !oSettings.cases?toLowerCase(a.s):a.s
  193. ,sB = !oSettings.cases?toLowerCase(b.s):b.s;
  194. // maybe force Strings
  195. // var bAString = typeof(sA)=='string';
  196. // var bBString = typeof(sB)=='string';
  197. // if (!oSettings.forceStrings&&(bAString||bBString)) {
  198. // if (!bAString) sA = ''+sA;
  199. // if (!bBString) sB = ''+sB;
  200. if (!oSettings.forceStrings) {
  201. // maybe mixed
  202. var aAnum = sA&&sA.match(rxLastNr)
  203. ,aBnum = sB&&sB.match(rxLastNr);
  204. if (aAnum&&aBnum) {
  205. var sAprv = sA.substr(0,sA.length-aAnum[0].length)
  206. ,sBprv = sB.substr(0,sB.length-aBnum[0].length);
  207. if (sAprv==sBprv) {
  208. bNumeric = !fls;
  209. sA = prsflt(aAnum[0]);
  210. sB = prsflt(aBnum[0]);
  211. }
  212. }
  213. }
  214. // return sort-integer
  215. var iReturn = iAsc*(sA<sB?-1:(sA>sB?1:0));
  216. // test for non latin chars
  217. if (!bNumeric&&oSettings.charOrder) {
  218. if (bDoubles) { // first replace doubles
  219. for (var s in oReplace) {
  220. var o = oReplace[s];
  221. sA = sA.replace(s,o);
  222. sB = sB.replace(s,o);
  223. }
  224. }
  225. // then test if either word has non latin chars
  226. // we're using the slower string.match because strangely regex.test sometimes fails
  227. if (sA.match(rxNotLatin)!==nll||sB.match(rxNotLatin)!==nll) {
  228. for (var k=0,l=mathmn(sA.length,sB.length);k<l;k++) {
  229. var iAchr = aOrderChar.indexOf(sA[k])
  230. ,iBchr = aOrderChar.indexOf(sB[k]);
  231. if (iReturn=iAsc*(iAchr<iBchr?-1:(iAchr>iBchr?1:0))) break;
  232. }
  233. }
  234. }
  235. return iReturn;
  236. };
  237. oThis.each(function(i,el) {
  238. var $Elm = $(el)
  239. // element or sub selection
  240. ,mElmOrSub = bFind?(bFilter?$Filter.filter(el):$Elm.find(_find)):$Elm
  241. // text or attribute value
  242. ,sSort = bData?''+mElmOrSub.data(oSettings.data):(bAttr?mElmOrSub.attr(oSettings.attr):(oSettings.useVal?mElmOrSub.val():mElmOrSub.text()))
  243. // to sort or not to sort
  244. ,mParent = $Elm.parent();
  245. if (!oElements[mParent]) oElements[mParent] = {s:[],n:[]}; // s: sort, n: not sort
  246. if (mElmOrSub.length>0) oElements[mParent].s.push({s:sSort,e:$Elm,n:i}); // s:string, e:element, n:number
  247. else oElements[mParent].n.push({e:$Elm,n:i});
  248. });
  249. //
  250. // sort
  251. for (sParent in oElements) oElements[sParent].s.sort(fnSort);
  252. //
  253. // order elements and fill new order
  254. for (sParent in oElements) {
  255. var oParent = oElements[sParent]
  256. ,aOrg = [] // list for original position
  257. ,iLow = iLen
  258. ,aCnt = [0,0] // count how much we've sorted for retreival from either the sort list or the non-sort list (oParent.s/oParent.n)
  259. ,i;
  260. switch (oSettings.place) {
  261. case 'first': $.each(oParent.s,function(i,obj) { iLow = mathmn(iLow,obj.n) }); break;
  262. case 'org': $.each(oParent.s,function(i,obj) { aOrg.push(obj.n) }); break;
  263. case 'end': iLow = oParent.n.length; break;
  264. default: iLow = 0;
  265. }
  266. for (i = 0;i<iLen;i++) {
  267. var bSList = contains(aOrg,i)?!fls:i>=iLow&&i<iLow+oParent.s.length
  268. ,mEl = (bSList?oParent.s:oParent.n)[aCnt[bSList?0:1]].e;
  269. mEl.parent().append(mEl);
  270. if (bSList||!oSettings.returns) aNewOrder.push(mEl.get(0));
  271. aCnt[bSList?0:1]++;
  272. }
  273. }
  274. oThis.length = 0;
  275. Array.prototype.push.apply(oThis,aNewOrder);
  276. return oThis;
  277. }
  278. });
  279. // toLowerCase
  280. function toLowerCase(s) {
  281. return s&&s.toLowerCase?s.toLowerCase():s;
  282. }
  283. // array contains
  284. function contains(a,n) {
  285. for (var i=0,l=a.length;i<l;i++) if (a[i]==n) return !fls;
  286. return fls;
  287. }
  288. // set functions
  289. $.fn.TinySort = $.fn.Tinysort = $.fn.tsort = $.fn.tinysort;
  290. })(jQuery);