float.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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),
  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));
  35. const dot = str.indexOf('.');
  36. if (dot !== -1 && str[str.length - 1] === '0')
  37. node.minFractionDigits = str.length - dot - 1;
  38. return node;
  39. },
  40. stringify: stringifyNumber.stringifyNumber
  41. };
  42. exports.float = float;
  43. exports.floatExp = floatExp;
  44. exports.floatNaN = floatNaN;