Allow multiple objects with the same key
This commit is contained in:
parent
3bc8a84523
commit
f073019670
2 changed files with 40 additions and 4 deletions
19
index.js
19
index.js
|
@ -9,21 +9,32 @@ export function parse(rinput) {
|
|||
let input = rinput.split("\n").map(v => v.trim()).filter(v => v.length > 0)
|
||||
let object = {}
|
||||
let object_key = ""
|
||||
let object_buffer = ""
|
||||
let object_buffer = {}
|
||||
let object_value_buffer = ""
|
||||
let object_open = false
|
||||
|
||||
for (let line of input) {
|
||||
if (line.endsWith("{")) {
|
||||
object_key = line.replaceAll("{", "").trim()
|
||||
object[object_key] = {}
|
||||
object_buffer = ""
|
||||
object_buffer = {}
|
||||
object_value_buffer = ""
|
||||
object_open = true
|
||||
} else if (line.endsWith("}")) {
|
||||
object_open = false
|
||||
if (object[object_key] != null) {
|
||||
if (Array.isArray(object[object_key])) {
|
||||
object[object_key].push(object_buffer)
|
||||
} else {
|
||||
let old_obj = object[object_key]
|
||||
object[object_key] = [old_obj, object_buffer]
|
||||
}
|
||||
} else {
|
||||
object[object_key] = object_buffer
|
||||
}
|
||||
} else {
|
||||
let { key, value } = parse_value(line)
|
||||
if (object_open === true) {
|
||||
object[object_key][key] = value
|
||||
object_buffer[key] = value
|
||||
} else {
|
||||
object[key] = value
|
||||
}
|
||||
|
|
25
test/test.js
25
test/test.js
|
@ -47,6 +47,21 @@ object2 {
|
|||
}
|
||||
`
|
||||
|
||||
const MULTIPLE_OBJECT_WITH_SAME_KEY =
|
||||
`value {
|
||||
k: 1
|
||||
}
|
||||
|
||||
value {
|
||||
k: 2
|
||||
}
|
||||
|
||||
value {
|
||||
v: 1
|
||||
y: "x"
|
||||
}
|
||||
`
|
||||
|
||||
describe("#parse()", () => {
|
||||
it("should parse simple KV values", () => {
|
||||
deepStrictEqual({
|
||||
|
@ -98,4 +113,14 @@ describe("#parse()", () => {
|
|||
},
|
||||
}, parse(OBJECT_AND_SIMPLE_VALUES))
|
||||
})
|
||||
|
||||
it("should parse objects with the same key", () => {
|
||||
deepStrictEqual({
|
||||
"value": [
|
||||
{"k": 1},
|
||||
{"k": 2},
|
||||
{"v": 1, "y": "x"},
|
||||
]
|
||||
}, parse(MULTIPLE_OBJECT_WITH_SAME_KEY))
|
||||
})
|
||||
})
|
||||
|
|
Loading…
Reference in a new issue