https://github.com/cordx56/jsdrink
Simple parser combinators library written in TypeScript
https://github.com/cordx56/jsdrink
parser parser-combinators typescript
Last synced: about 1 year ago
JSON representation
Simple parser combinators library written in TypeScript
- Host: GitHub
- URL: https://github.com/cordx56/jsdrink
- Owner: cordx56
- License: mit
- Created: 2022-09-05T05:19:53.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2022-09-07T01:48:56.000Z (almost 4 years ago)
- Last Synced: 2025-05-03T06:11:40.086Z (about 1 year ago)
- Topics: parser, parser-combinators, typescript
- Language: TypeScript
- Homepage:
- Size: 179 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# jsdrink - simple parser combinators library
[](https://github.com/cordx56/jsdrink/blob/main/package.json)
[](https://www.npmjs.com/package/jsdrink)
[](https://github.com/cordx56/jsdrink/actions)
[](https://github.com/cordx56/jsdrink/blob/main/LICENSE)
jsdrink is a simple parser combinators library written in TypeScript, ported from [cordx56/godrink](https://github.com/cordx56/godrink).
## Feature
jsdrink is a simple, lightweight library.
jsdrink does not depend on non-standard libraries except dev-dependencies.
jsdrink reads input bytes or string and applies parsers in sequence and parses them into the desired structures.
## Documentation
See [https://cordx.net/jsdrink/](https://cordx.net/jsdrink/).
## Example
### Example code
Here is an example of a calculator.
```typescript
import { ParseResult, tf, sequence, any, many0 } from "jsdrink";
import { string, space0 } from "jsdrink/string";
import { integer } from "jsdrink/number";
const expr = (input: string): ParseResult => {
return tf(
sequence(
term,
many0(
tf(
sequence(space0, any(string("+"), string("-")), space0, term),
(parsed) => {
if (parsed[1] == "+") {
return parsed[3];
} else if (parsed[1] == "-") {
return -1 * parsed[3];
} else {
return 0;
}
}
)
)
),
(parsed) => {
return parsed[0] + parsed[1].reduce((sum, elem) => sum + elem, 0);
}
)(input);
};
const term = (input: string): ParseResult => {
return tf(
sequence(
factor,
many0(
tf(
sequence(space0, any(string("*"), string("/")), space0, factor),
(parsed) => {
if (parsed[1] == "*") {
return parsed[3];
} else if (parsed[1] == "/") {
return 1 / parsed[3];
} else {
return 0;
}
}
)
)
),
(parsed) => {
return parsed[0] * parsed[1].reduce((sum, elem) => sum * elem, 1);
}
)(input);
};
const factor = (input: string): ParseResult => {
return any(
integer,
tf(sequence(string("("), space0, expr, space0, string(")")), (parsed) => {
return parsed[2];
})
)(input);
};
console.log(expr("3 / (1 + 2) * 9").parsed); // 9
```