Allow multiple objects with the same key

This commit is contained in:
Sofía Aritz 2023-05-15 17:02:24 +02:00
parent 3bc8a84523
commit f073019670
2 changed files with 40 additions and 4 deletions

View file

@ -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
}

View file

@ -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))
})
})