/
parseInput.js
71 lines (65 loc) · 1.87 KB
/
parseInput.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
export default function parseInput(input) {
//following code is to make a best guess at
//the type for a variable being submitted.
//we are working with a serialized data representation
input = input.trim();
try {
input = JSON.stringify(
JSON.parse(input)
);
if (input[0] === '[') {
//array
return formatResponse('array', JSON.parse(input));
} else if (input[0] === '{') {
//object
return formatResponse('object', JSON.parse(input));
} else if (
input.match(/\-?\d+\.\d+/)
&& input.match(/\-?\d+\.\d+/)[0] === input
) {
//integer
return formatResponse('float', parseFloat(input));
} else if (
input.match(/\-?\d+/)
&& input.match(/\-?\d+/)[0] === input
) {
//float
return formatResponse('integer', parseInt(input));
}
} catch (e) {
// no-op
}
//run in case input was not serializable
input = input.toLowerCase();
switch (input) {
case 'undefined': {
return formatResponse('undefined', undefined);
}
case 'nan': {
return formatResponse('nan', NaN);
}
case 'null': {
return formatResponse('null', null);
}
case 'true': {
return formatResponse('boolean', true);
}
case 'false': {
return formatResponse('boolean', false);
}
default: {
//check to see if this is a date
input = Date.parse(input);
if (input) {
return (formatResponse('date', new Date(input)));
}
}
}
return formatResponse(false, null);
}
function formatResponse(type, value) {
return {
type: type,
value: value
};
}