float.js 1.6 KB

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