76871547c2d5b39fbb02d7748378054a72aa0a8d
[yaffs-website] / node_modules / grunt / node_modules / js-yaml / lib / js-yaml / type / float.js
1 'use strict';
2
3 var common = require('../common');
4 var Type   = require('../type');
5
6 var YAML_FLOAT_PATTERN = new RegExp(
7   '^(?:[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+][0-9]+)?' +
8   '|\\.[0-9_]+(?:[eE][-+][0-9]+)?' +
9   '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
10   '|[-+]?\\.(?:inf|Inf|INF)' +
11   '|\\.(?:nan|NaN|NAN))$');
12
13 function resolveYamlFloat(data) {
14   if (data === null) return false;
15
16   if (!YAML_FLOAT_PATTERN.test(data)) return false;
17
18   return true;
19 }
20
21 function constructYamlFloat(data) {
22   var value, sign, base, digits;
23
24   value  = data.replace(/_/g, '').toLowerCase();
25   sign   = value[0] === '-' ? -1 : 1;
26   digits = [];
27
28   if ('+-'.indexOf(value[0]) >= 0) {
29     value = value.slice(1);
30   }
31
32   if (value === '.inf') {
33     return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
34
35   } else if (value === '.nan') {
36     return NaN;
37
38   } else if (value.indexOf(':') >= 0) {
39     value.split(':').forEach(function (v) {
40       digits.unshift(parseFloat(v, 10));
41     });
42
43     value = 0.0;
44     base = 1;
45
46     digits.forEach(function (d) {
47       value += d * base;
48       base *= 60;
49     });
50
51     return sign * value;
52
53   }
54   return sign * parseFloat(value, 10);
55 }
56
57
58 var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
59
60 function representYamlFloat(object, style) {
61   var res;
62
63   if (isNaN(object)) {
64     switch (style) {
65       case 'lowercase': return '.nan';
66       case 'uppercase': return '.NAN';
67       case 'camelcase': return '.NaN';
68     }
69   } else if (Number.POSITIVE_INFINITY === object) {
70     switch (style) {
71       case 'lowercase': return '.inf';
72       case 'uppercase': return '.INF';
73       case 'camelcase': return '.Inf';
74     }
75   } else if (Number.NEGATIVE_INFINITY === object) {
76     switch (style) {
77       case 'lowercase': return '-.inf';
78       case 'uppercase': return '-.INF';
79       case 'camelcase': return '-.Inf';
80     }
81   } else if (common.isNegativeZero(object)) {
82     return '-0.0';
83   }
84
85   res = object.toString(10);
86
87   // JS stringifier can build scientific format without dots: 5e-100,
88   // while YAML requres dot: 5.e-100. Fix it with simple hack
89
90   return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
91 }
92
93 function isFloat(object) {
94   return (Object.prototype.toString.call(object) === '[object Number]') &&
95          (object % 1 !== 0 || common.isNegativeZero(object));
96 }
97
98 module.exports = new Type('tag:yaml.org,2002:float', {
99   kind: 'scalar',
100   resolve: resolveYamlFloat,
101   construct: constructYamlFloat,
102   predicate: isFloat,
103   represent: representYamlFloat,
104   defaultStyle: 'lowercase'
105 });