-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
62 lines (47 loc) · 1.08 KB
/
index.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
'use strict'
var REGEX = {
TRIM_QUOTES: /"/g
}
function isKeyValue (str) {
return str.indexOf(':') !== -1
}
function hasQuote (str) {
return str.toString().indexOf('"') !== -1
}
function addKeyValue (json, item) {
item = item.split(':')
var key = item[0]
var value = item[1]
if (json[key]) {
if (!Array.isArray(json[key])) json[key] = [json[key], value]
else json[key].push(value)
} else json[key] = value
}
var buffer = ''
var bufferCalls = 0
function addText (json, item) {
if (!hasQuote(item)) {
if (json.text) json.text += item
else json.text = item
return
}
var separator = buffer ? buffer + ' ' : ''
buffer = separator + item
if (++bufferCalls === 2) {
addKeyValue(json, buffer.replace(REGEX.TRIM_QUOTES, ''))
buffer = null
bufferCalls = 0
}
}
function dsl (input) {
input = input.split(' ')
var index = -1
var json = {}
while (input[++index]) {
var item = input[index]
if (isKeyValue(item) && !hasQuote(item)) addKeyValue(json, item)
else addText(json, item)
}
return json
}
module.exports = dsl