unit.js 2.4 KB

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