m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMarcin Chrzanowski <marcin.j.chrzanowski@gmail.com>2017-07-19 23:13:41 -0400
committerMarcin Chrzanowski <marcin.j.chrzanowski@gmail.com>2017-07-19 23:40:18 -0400
commitbe3415a7cb219fe0244e726ccd0f232485672ed6 (patch)
tree79d4f567116da67b82e93a162e0f67cd2dc6a8d0
parent3fccdd3d61d96d3c979f72c7a9d9c26420ae3656 (diff)
Lex and parse explosions
-rw-r--r--__tests__/lexer.test.js12
-rw-r--r--__tests__/parser.test.js12
-rw-r--r--index.js2
-rw-r--r--src/lexer.js1
-rw-r--r--src/parser.js8
5 files changed, 35 insertions, 0 deletions
diff --git a/__tests__/lexer.test.js b/__tests__/lexer.test.js
index b9260b8..3003fb9 100644
--- a/__tests__/lexer.test.js
+++ b/__tests__/lexer.test.js
@@ -124,4 +124,16 @@ describe('lex', () => {
])
})
})
+
+ describe('exploding dice', () => {
+ test('1E1d6', () => {
+ expect(lex('1E1d6')).toEqual([
+ { type: 'constant', value: 1 },
+ { type: 'E' },
+ { type: 'constant', value: 1 },
+ { type: 'd' },
+ { type: 'constant', value: 6 }
+ ])
+ })
+ })
})
diff --git a/__tests__/parser.test.js b/__tests__/parser.test.js
index 47944d2..26febef 100644
--- a/__tests__/parser.test.js
+++ b/__tests__/parser.test.js
@@ -115,6 +115,18 @@ describe('parse', () => {
})
})
+ it('parses exploding dice', () => {
+ expect(parse('1E1d6')).toEqual({
+ type: 'E',
+ left: { type: 'constant', value: 1 },
+ right: {
+ type: 'd',
+ left: { type: 'constant', value: 1 },
+ right: { type: 'constant', value: 6 }
+ }
+ })
+ })
+
describe('parsing parentheses', () => {
test('(1d6)d6', () => {
expect(parse('(1d6)d6')).toEqual({
diff --git a/index.js b/index.js
index 8cdfe1e..3b858a2 100644
--- a/index.js
+++ b/index.js
@@ -7,6 +7,8 @@ const interpret = tree => {
return D.constant(tree.value)
case 'd':
return D.d(interpret(tree.left), interpret(tree.right))
+ case 'E':
+ return D.explode(interpret(tree.left), interpret(tree.right))
case 'add':
return D.add(interpret(tree.left), interpret(tree.right))
case 'subtract':
diff --git a/src/lexer.js b/src/lexer.js
index 5e29e42..85579fb 100644
--- a/src/lexer.js
+++ b/src/lexer.js
@@ -24,6 +24,7 @@ newLexemeType('+', '\\+')
newLexemeType('-', '-')
newLexemeType('(', '\\(')
newLexemeType(')', '\\)')
+newLexemeType('E', 'E')
newSkippableLexeme('whitespace', '\\s+')
const lex = (expressionString) => {
diff --git a/src/parser.js b/src/parser.js
index 3437f1a..9479abc 100644
--- a/src/parser.js
+++ b/src/parser.js
@@ -47,6 +47,14 @@ newSymbol('d', (parser) => {
}
})
+newSymbol('E', null, 30, (left, parser) => {
+ return {
+ type: 'E',
+ left: left,
+ right: parser.expression(29)
+ }
+})
+
newSymbol('+', null, 20, (left, parser) => {
return {
type: 'add',