unit.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. // Check if three code points would start a number
  7. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  8. function likeNumber(value) {
  9. var code = value.charCodeAt(0);
  10. var nextCode;
  11. if (code === plus || code === minus) {
  12. nextCode = value.charCodeAt(1);
  13. if (nextCode >= 48 && nextCode <= 57) {
  14. return true;
  15. }
  16. var nextNextCode = value.charCodeAt(2);
  17. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  18. return true;
  19. }
  20. return false;
  21. }
  22. if (code === dot) {
  23. nextCode = value.charCodeAt(1);
  24. if (nextCode >= 48 && nextCode <= 57) {
  25. return true;
  26. }
  27. return false;
  28. }
  29. if (code >= 48 && code <= 57) {
  30. return true;
  31. }
  32. return false;
  33. }
  34. // Consume a number
  35. // https://www.w3.org/TR/css-syntax-3/#consume-number
  36. module.exports = function(value) {
  37. var pos = 0;
  38. var length = value.length;
  39. var code;
  40. var nextCode;
  41. var nextNextCode;
  42. if (length === 0 || !likeNumber(value)) {
  43. return false;
  44. }
  45. code = value.charCodeAt(pos);
  46. if (code === plus || code === minus) {
  47. pos++;
  48. }
  49. while (pos < length) {
  50. code = value.charCodeAt(pos);
  51. if (code < 48 || code > 57) {
  52. break;
  53. }
  54. pos += 1;
  55. }
  56. code = value.charCodeAt(pos);
  57. nextCode = value.charCodeAt(pos + 1);
  58. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  59. pos += 2;
  60. while (pos < length) {
  61. code = value.charCodeAt(pos);
  62. if (code < 48 || code > 57) {
  63. break;
  64. }
  65. pos += 1;
  66. }
  67. }
  68. code = value.charCodeAt(pos);
  69. nextCode = value.charCodeAt(pos + 1);
  70. nextNextCode = value.charCodeAt(pos + 2);
  71. if (
  72. (code === exp || code === EXP) &&
  73. ((nextCode >= 48 && nextCode <= 57) ||
  74. ((nextCode === plus || nextCode === minus) &&
  75. nextNextCode >= 48 &&
  76. nextNextCode <= 57))
  77. ) {
  78. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  79. while (pos < length) {
  80. code = value.charCodeAt(pos);
  81. if (code < 48 || code > 57) {
  82. break;
  83. }
  84. pos += 1;
  85. }
  86. }
  87. return {
  88. number: value.slice(0, pos),
  89. unit: value.slice(pos)
  90. };
  91. };