Last active
October 1, 2022 22:33
-
-
Save djedr/681e0199859874b3324eaa84192c4210 to your computer and use it in GitHub Desktop.
A simple data format built on Jevko
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// run this script with | |
// | |
// node --experimental-network-imports easyjevko.js | |
// | |
// on Node.js or | |
// | |
// deno run --allow-net easyjevko.js | |
// | |
// on Deno | |
import("https://cdn.jsdelivr.net/gh/jevko/[email protected]/mod.js").then(({parseJevko}) => { | |
const v = parseJevko(` | |
hello [world] | |
list [[1][2][3]] | |
`) | |
console.log(toValue(v)) | |
// this should print | |
// Map { "hello" => "world", "list" => [ "1", "2", "3" ] } | |
}) | |
const fromValue = (value) => { | |
if (typeof value === 'string') { | |
let suffix = '' | |
for (const c of value) { | |
if (c === open || c === close || c === escape) suffix += escape | |
suffix += c | |
} | |
return {subjevkos: [], suffix} | |
} | |
if (value instanceof Map) { | |
const subjevkos = [] | |
if (value.size === 0) throw Error(`Empty Map not allowed`) | |
else if (value.has('')) throw Error(`Empty key not allowed`) | |
else for (const [k, v] of value) { | |
if (typeof k !== 'string') throw Error(`Nonstring keys not allowed`) | |
subjevkos.push({prefix: k, jevko: fromValue(v)}) | |
} | |
return {subjevkos, suffix: ''} | |
} | |
if (Array.isArray(value)) { | |
const subjevkos = [] | |
if (value.length === 0) throw Error(`Empty Array not allowed`) | |
else for (const v of value) { | |
subjevkos.push({prefix: '', jevko: fromValue(v)}) | |
} | |
return {subjevkos, suffix: ''} | |
} | |
throw Error(`Unrecognized value: ${value}`) | |
} | |
const toValue = (jevko) => { | |
const {subjevkos, suffix} = jevko | |
if (subjevkos.length === 0) return suffix | |
if (suffix.trim() !== '') throw Error('nonempty suffix') | |
const {prefix} = subjevkos[0] | |
if (prefix.trim() === '') { | |
const ret = [] | |
for (const {prefix, jevko} of subjevkos) { | |
if (prefix.trim() !== '') throw Error('nonempty prefix') | |
ret.push(toValue(jevko)) | |
} | |
return ret | |
} | |
const ret = new Map() | |
for (const {prefix, jevko} of subjevkos) { | |
const key = prefix.trim() | |
if (ret.has(key)) throw Error(`key ${key} duplicated!`) | |
ret.set(key, toValue(jevko)) | |
} | |
return ret | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment