number-tokens.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const isDigit = (char) => char >= '0' && char <= '9';
  2. export function parseNumberToken(src, pos) {
  3. const char = src[pos];
  4. if (isDigit(char)) {
  5. let digits = char;
  6. while (true) {
  7. const next = src[++pos];
  8. if (isDigit(next))
  9. digits += next;
  10. else
  11. return { char: '0', digits, width: digits.length };
  12. }
  13. }
  14. switch (char) {
  15. case '#': {
  16. let width = 1;
  17. while (src[++pos] === '#')
  18. ++width;
  19. return { char, width };
  20. }
  21. case '@': {
  22. let min = 1;
  23. while (src[++pos] === '@')
  24. ++min;
  25. let width = min;
  26. pos -= 1;
  27. while (src[++pos] === '#')
  28. ++width;
  29. return { char, min, width };
  30. }
  31. case 'E': {
  32. const plus = src[pos + 1] === '+';
  33. if (plus)
  34. ++pos;
  35. let expDigits = 0;
  36. while (src[++pos] === '0')
  37. ++expDigits;
  38. const width = (plus ? 2 : 1) + expDigits;
  39. if (expDigits)
  40. return { char, expDigits, plus, width };
  41. else
  42. break;
  43. }
  44. case '.':
  45. case ',':
  46. return { char, width: 1 };
  47. }
  48. return null;
  49. }