-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·122 lines (98 loc) · 2.44 KB
/
index.js
File metadata and controls
executable file
·122 lines (98 loc) · 2.44 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#! /usr/bin/env node
const yargs = require('yargs')
const set = require('lodash.set')
const get = require('lodash.get')
const reduce = require('lodash.reduce')
const forEach = require('lodash.foreach')
const argv = yargs
.usage('Usage: $0 <keys> [options]')
.alias('p', 'pretty')
.alias('t', 'type')
.alias('h', 'help')
.boolean('pretty')
.describe('p', 'Pretty print JSON output')
.describe('t', 'Type for a key. Format: key=value')
.example('$0 homer=dad marge=mom bart=son lisa=daughter maggie=daughter', 'count the lines in the given file')
.help('help')
.argv
const vtypes = {
'string': function(v) {
return v.toString()
},
number(v) {
const parsed = parseFloat(v)
if (isNaN(parsed) || parsed.toString() !== v) {
throw new Error(`${v} is not a valid number`);
}
return parsed;
}
};
function keyValueParse(strings, types) {
strings = strings || []
strings = Array.isArray(strings) ? strings : [ strings ]
return strings.reduce((result, str) => {
const pair = str.split('=')
const key = pair[0]
const value = typify(key, pair[1], types)
if (!key) {
throw new Error('Error parsing key')
}
result[key] = value
return result
}, {})
};
function typify(key, value, types) {
if (!types) {
return value;
}
const transform = vtypes[get(types, key)];
if (transform) {
return transform(value)
} else {
return guessType(value)
}
}
function guessType(v) {
const handlers = [vtypes.number, vtypes.string]
if (!v) {
return null
}
forEach(handlers, (transform) => {
try {
v = transform(v)
return false
} catch (e) {
return true
}
})
return v;
}
function checkTypes(types) {
forEach(types, (t, k) => {
if (!vtypes[t]) {
throw new Error(`Invalid type ${t} for key ${k}`)
}
})
}
function generateJSONObject(kvObject) {
return reduce(kvObject, (result, value, key) => {
set(result, key, value);
return result;
}, {});
}
function generateJSONString(obj, pretty) {
return JSON.stringify(obj, null, pretty ? 2 : null)
}
try {
const types = keyValueParse(argv.type) || {};
checkTypes(types);
const jsonObject = generateJSONObject(keyValueParse(argv._, types))
const jsonString = generateJSONString(jsonObject, argv.pretty)
console.log(jsonString)
} catch (e) {
if (typeof e === 'object' && e.message) {
console.log(e.message)
} else {
console.log(e)
}
}