unit.js 953 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. var minus = "-".charCodeAt(0);
  2. var plus = "+".charCodeAt(0);
  3. var dot = ".".charCodeAt(0);
  4. var exp = "e".charCodeAt(0);
  5. var EXP = "E".charCodeAt(0);
  6. module.exports = function(value) {
  7. var pos = 0;
  8. var length = value.length;
  9. var dotted = false;
  10. var sciPos = -1;
  11. var containsNumber = false;
  12. var code;
  13. while (pos < length) {
  14. code = value.charCodeAt(pos);
  15. if (code >= 48 && code <= 57) {
  16. containsNumber = true;
  17. } else if (code === exp || code === EXP) {
  18. if (sciPos > -1) {
  19. break;
  20. }
  21. sciPos = pos;
  22. } else if (code === dot) {
  23. if (dotted) {
  24. break;
  25. }
  26. dotted = true;
  27. } else if (code === plus || code === minus) {
  28. if (pos !== 0) {
  29. break;
  30. }
  31. } else {
  32. break;
  33. }
  34. pos += 1;
  35. }
  36. if (sciPos + 1 === pos) pos--;
  37. return containsNumber
  38. ? {
  39. number: value.slice(0, pos),
  40. unit: value.slice(pos)
  41. }
  42. : false;
  43. };