Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81149 views
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 (null === data) {
15
return false;
16
}
17
18
var value, sign, base, digits;
19
20
if (!YAML_FLOAT_PATTERN.test(data)) {
21
return false;
22
}
23
return true;
24
}
25
26
function constructYamlFloat(data) {
27
var value, sign, base, digits;
28
29
value = data.replace(/_/g, '').toLowerCase();
30
sign = '-' === value[0] ? -1 : 1;
31
digits = [];
32
33
if (0 <= '+-'.indexOf(value[0])) {
34
value = value.slice(1);
35
}
36
37
if ('.inf' === value) {
38
return (1 === sign) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
39
40
} else if ('.nan' === value) {
41
return NaN;
42
43
} else if (0 <= value.indexOf(':')) {
44
value.split(':').forEach(function (v) {
45
digits.unshift(parseFloat(v, 10));
46
});
47
48
value = 0.0;
49
base = 1;
50
51
digits.forEach(function (d) {
52
value += d * base;
53
base *= 60;
54
});
55
56
return sign * value;
57
58
}
59
return sign * parseFloat(value, 10);
60
}
61
62
function representYamlFloat(object, style) {
63
if (isNaN(object)) {
64
switch (style) {
65
case 'lowercase':
66
return '.nan';
67
case 'uppercase':
68
return '.NAN';
69
case 'camelcase':
70
return '.NaN';
71
}
72
} else if (Number.POSITIVE_INFINITY === object) {
73
switch (style) {
74
case 'lowercase':
75
return '.inf';
76
case 'uppercase':
77
return '.INF';
78
case 'camelcase':
79
return '.Inf';
80
}
81
} else if (Number.NEGATIVE_INFINITY === object) {
82
switch (style) {
83
case 'lowercase':
84
return '-.inf';
85
case 'uppercase':
86
return '-.INF';
87
case 'camelcase':
88
return '-.Inf';
89
}
90
} else if (common.isNegativeZero(object)) {
91
return '-0.0';
92
}
93
return object.toString(10);
94
}
95
96
function isFloat(object) {
97
return ('[object Number]' === Object.prototype.toString.call(object)) &&
98
(0 !== object % 1 || common.isNegativeZero(object));
99
}
100
101
module.exports = new Type('tag:yaml.org,2002:float', {
102
kind: 'scalar',
103
resolve: resolveYamlFloat,
104
construct: constructYamlFloat,
105
predicate: isFloat,
106
represent: representYamlFloat,
107
defaultStyle: 'lowercase'
108
});
109
110