-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcast.js
More file actions
31 lines (28 loc) · 707 Bytes
/
cast.js
File metadata and controls
31 lines (28 loc) · 707 Bytes
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
const types = {
string: value => `${value}`,
int: (value) => {
if (!parseInt(value, 10)) {
throw new TypeError(`${value} is not an integer`);
}
return parseInt(value, 10);
},
float: (value) => {
if (!parseFloat(value)) {
throw new TypeError(`${value} is not a number`);
}
return parseFloat(value);
},
bool: (value) => {
if (!(value === 'true' || value === 'false')) {
throw new TypeError(`${value} is not a boolean`);
}
return value === 'true';
},
};
module.exports = (value, type = 'string') => {
const castFn = types[type];
if (!castFn) {
throw new TypeError(`${type} is not a supported type`);
}
return castFn(value);
};