index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * @version 1.4.0
  3. * @date 2015-10-26
  4. * @stability 3 - Stable
  5. * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
  6. * @license MIT License
  7. */
  8. var naturalCompare = function(a, b) {
  9. var i, codeA
  10. , codeB = 1
  11. , posA = 0
  12. , posB = 0
  13. , alphabet = String.alphabet
  14. function getCode(str, pos, code) {
  15. if (code) {
  16. for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
  17. return +str.slice(pos - 1, i)
  18. }
  19. code = alphabet && alphabet.indexOf(str.charAt(pos))
  20. return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code
  21. : code < 46 ? 65 // -
  22. : code < 48 ? code - 1
  23. : code < 58 ? code + 18 // 0-9
  24. : code < 65 ? code - 11
  25. : code < 91 ? code + 11 // A-Z
  26. : code < 97 ? code - 37
  27. : code < 123 ? code + 5 // a-z
  28. : code - 63
  29. }
  30. if ((a+="") != (b+="")) for (;codeB;) {
  31. codeA = getCode(a, posA++)
  32. codeB = getCode(b, posB++)
  33. if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
  34. codeA = getCode(a, posA, posA)
  35. codeB = getCode(b, posB, posA = i)
  36. posB = i
  37. }
  38. if (codeA != codeB) return (codeA < codeB) ? -1 : 1
  39. }
  40. return 0
  41. }
  42. try {
  43. module.exports = naturalCompare;
  44. } catch (e) {
  45. String.naturalCompare = naturalCompare;
  46. }