crazy-parser
v1.6.0
Published
A light-weight parser combinator
Maintainers
Readme
Crazy Parser
A light-weight parser combinator.
Install
npm i crazy-parserExample
Sign Parser
Import:
import {char} from "crazy-parser"Build a sign parser:
const pSign = char("+").or(char("-")) Represent it with booleans:
const pSign =
char("+").cmap(true)
.or(char("-").cmap(false))Parse a sign:
console.log(pSign.eval("+")) // true
console.log(pSign.eval("-")) // false
console.log(pSign.eval("???") instanceof Error) // trueAdd custom error messages:
class MissingSign extends Error {}
const pSign =
char("+").cmap(true)
.or(char("-").cmap(false))
.error(new MissingSign())Time Parser
import {digit} from "crazy-parser"
// Parse current hour
const d24 =
// 2 digits
digit.x(2)
// Map them to a number
.map(cs => parseInt(cs.join("")))
// Add a constrain
.where(x => 0 <= x && x <= 23)
// Parse current minute & second
const d60 = digit.x(2)
.map(cs => parseInt(cs.join("")))
.where(h => 0 <= h && h <= 59)
// Insert colons between them
const time = template`${d24}:${d60}:${d60}`
// There shouldn't be anything else after the time
._$(eof)
console.log(time.eval("12:34:56"))
console.log(time.eval("12:34:56?") instanceof Error) // true
console.log(time.eval("99:99:99") instanceof Error) // true
console.log(time.eval("9:9:9") instanceof Error) // trueYou can go to test folder for more examples. If you'd like to read the docs and the signatures, please go to the main module.
Development
Using make
Please make sure you have node, tsc and vitest installed.
Build
makeBuild a tarball
make packClean up
make cleanTest
The test takes about 6 seconds on my machine.
make testUsing npm
Please make sure you have tsc and vitest installed.
Build
npm run buildBuild a tarball
npm run build
npm packClean up
npm run cleanTest
npm run clean
npm run test