Skip to content

Instantly share code, notes, and snippets.

@tluyben
Created July 5, 2023 08:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tluyben/0f9877bbe657d5f49122357f4a99d5c8 to your computer and use it in GitHub Desktop.
Save tluyben/0f9877bbe657d5f49122357f4a99d5c8 to your computer and use it in GitHub Desktop.
simple s-expression parser for typescript
export function parse(lisp: string) {
const lexer = /"[^"]*"|\(|\)|[^\s()]+/g;
const ts = lisp.match(lexer)!;
let i = 0
const rec = () => {
let prg: any = undefined
while (i < ts.length) {
if (ts[i] === '(') {
if (!prg) {
prg = []
} else {
prg.push(rec())
}
} else if (ts[i] === ')') {
return prg
} else {
prg.push(ts[i])
}
i++
}
return prg
}
return rec()
}
const test = `
(progn
(dropempty query)
(keys result)
(drop result ('id 'access))
(first result)
(if (ne result 'status)
(return 'Error "You cannot update this" 401)
(else (return 'Success)))
`
console.log(JSON.stringify(parse(test)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment