You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
772 B

4 years ago
  1. // adapted from http://nedbatchelder.com/blog/200712.html#e20071211T054956
  2. var NUMBER_PATTERN = /([0-9]+)/;
  3. function naturalCompare(value1, value2) {
  4. var keys1 = ('' + value1).split(NUMBER_PATTERN).map(tryParseInt);
  5. var keys2 = ('' + value2).split(NUMBER_PATTERN).map(tryParseInt);
  6. var key1;
  7. var key2;
  8. var compareFirst = Math.min(keys1.length, keys2.length);
  9. var i, l;
  10. for (i = 0, l = compareFirst; i < l; i++) {
  11. key1 = keys1[i];
  12. key2 = keys2[i];
  13. if (key1 != key2) {
  14. return key1 > key2 ? 1 : -1;
  15. }
  16. }
  17. return keys1.length > keys2.length ? 1 : (keys1.length == keys2.length ? 0 : -1);
  18. }
  19. function tryParseInt(value) {
  20. return ('' + parseInt(value)) == value ?
  21. parseInt(value) :
  22. value;
  23. }
  24. module.exports = naturalCompare;