bootstrap-table-natural-sorting.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. (function (global, factory) {
  2. if (typeof define === "function" && define.amd) {
  3. define([], factory);
  4. } else if (typeof exports !== "undefined") {
  5. factory();
  6. } else {
  7. var mod = {
  8. exports: {}
  9. };
  10. factory();
  11. global.bootstrapTableNaturalSorting = mod.exports;
  12. }
  13. })(this, function () {
  14. "use strict";
  15. /**
  16. * @author: Brian Huisman
  17. * @webSite: http://www.greywyvern.com
  18. * @version: v1.0.0
  19. * JS functions to allow natural sorting on bootstrap-table columns
  20. * add data-sorter="alphanum" or data-sorter="numericOnly" to any th
  21. *
  22. * @update Dennis Hernández <http://djhvscf.github.io/Blog>
  23. * @update Duane May
  24. */
  25. function alphanum(a, b) {
  26. function chunkify(t) {
  27. var tz = [],
  28. x = 0,
  29. y = -1,
  30. n = 0,
  31. i,
  32. j;
  33. while (i = (j = t.charAt(x++)).charCodeAt(0)) {
  34. var m = i === 46 || i >= 48 && i <= 57;
  35. if (m !== n) {
  36. tz[++y] = "";
  37. n = m;
  38. }
  39. tz[y] += j;
  40. }
  41. return tz;
  42. }
  43. function stringfy(v) {
  44. if (typeof v === "number") {
  45. v = "" + v;
  46. }
  47. if (!v) {
  48. v = "";
  49. }
  50. return v;
  51. }
  52. var aa = chunkify(stringfy(a));
  53. var bb = chunkify(stringfy(b));
  54. for (x = 0; aa[x] && bb[x]; x++) {
  55. if (aa[x] !== bb[x]) {
  56. var c = Number(aa[x]),
  57. d = Number(bb[x]);
  58. if (c == aa[x] && d == bb[x]) {
  59. return c - d;
  60. } else {
  61. return aa[x] > bb[x] ? 1 : -1;
  62. }
  63. }
  64. }
  65. return aa.length - bb.length;
  66. }
  67. function numericOnly(a, b) {
  68. function stripNonNumber(s) {
  69. s = s.replace(new RegExp(/[^0-9]/g), "");
  70. return parseInt(s, 10);
  71. }
  72. return stripNonNumber(a) - stripNonNumber(b);
  73. }
  74. });