float.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { Scalar } from '../../nodes/Scalar.js';
  2. import { stringifyNumber } from '../../stringify/stringifyNumber.js';
  3. const floatNaN = {
  4. identify: value => typeof value === 'number',
  5. default: true,
  6. tag: 'tag:yaml.org,2002:float',
  7. test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
  8. resolve: (str) => str.slice(-3).toLowerCase() === 'nan'
  9. ? NaN
  10. : str[0] === '-'
  11. ? Number.NEGATIVE_INFINITY
  12. : Number.POSITIVE_INFINITY,
  13. stringify: stringifyNumber
  14. };
  15. const floatExp = {
  16. identify: value => typeof value === 'number',
  17. default: true,
  18. tag: 'tag:yaml.org,2002:float',
  19. format: 'EXP',
  20. test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
  21. resolve: (str) => parseFloat(str.replace(/_/g, '')),
  22. stringify(node) {
  23. const num = Number(node.value);
  24. return isFinite(num) ? num.toExponential() : stringifyNumber(node);
  25. }
  26. };
  27. const float = {
  28. identify: value => typeof value === 'number',
  29. default: true,
  30. tag: 'tag:yaml.org,2002:float',
  31. test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
  32. resolve(str) {
  33. const node = new Scalar(parseFloat(str.replace(/_/g, '')));
  34. const dot = str.indexOf('.');
  35. if (dot !== -1) {
  36. const f = str.substring(dot + 1).replace(/_/g, '');
  37. if (f[f.length - 1] === '0')
  38. node.minFractionDigits = f.length;
  39. }
  40. return node;
  41. },
  42. stringify: stringifyNumber
  43. };
  44. export { float, floatExp, floatNaN };