m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--__tests__/lexer.test.js24
-rw-r--r--__tests__/parser.test.js16
-rw-r--r--src/lexer.js1
-rw-r--r--src/parser.js8
4 files changed, 49 insertions, 0 deletions
diff --git a/__tests__/lexer.test.js b/__tests__/lexer.test.js
index 6434e17..e9115a1 100644
--- a/__tests__/lexer.test.js
+++ b/__tests__/lexer.test.js
@@ -64,4 +64,28 @@ describe('lex', () => {
])
})
})
+
+ describe('lexes subtraction', () => {
+ it('1d6 - 1d4', () => {
+ expect(lex('1d6 - 1d4')).toEqual([
+ { type: 'constant', value: 1 },
+ { type: 'd' },
+ { type: 'constant', value: 6 },
+ { type: '-' },
+ { type: 'constant', value: 1 },
+ { type: 'd' },
+ { type: 'constant', value: 4 }
+ ])
+ })
+
+ it('2d17 - 4', () => {
+ expect(lex('2d17 - 4')).toEqual([
+ { type: 'constant', value: 2 },
+ { type: 'd' },
+ { type: 'constant', value: 17 },
+ { type: '-' },
+ { type: 'constant', value: 4 }
+ ])
+ })
+ })
})
diff --git a/__tests__/parser.test.js b/__tests__/parser.test.js
index b0dc28d..6fe296c 100644
--- a/__tests__/parser.test.js
+++ b/__tests__/parser.test.js
@@ -56,4 +56,20 @@ describe('parse', () => {
}
})
})
+
+ it('parses dice subtraction', () => {
+ expect(parse('1d6 - 2d8')).toEqual({
+ type: 'subtract',
+ left: {
+ type: 'd',
+ left: { type: 'constant', value: 1 },
+ right: { type: 'constant', value: 6 }
+ },
+ right: {
+ type: 'd',
+ left: { type: 'constant', value: 2 },
+ right: { type: 'constant', value: 8 }
+ }
+ })
+ })
})
diff --git a/src/lexer.js b/src/lexer.js
index 97130d8..fd347c6 100644
--- a/src/lexer.js
+++ b/src/lexer.js
@@ -21,6 +21,7 @@ const newSkippableLexeme = (type, regex) => {
newValueLexeme('constant', '\\d+', Number)
newLexemeType('d', 'd')
newLexemeType('+', '\\+')
+newLexemeType('-', '-')
newSkippableLexeme('whitespace', '\\s+')
const lex = (expressionString) => {
diff --git a/src/parser.js b/src/parser.js
index c7d91c3..6c39c77 100644
--- a/src/parser.js
+++ b/src/parser.js
@@ -32,6 +32,14 @@ newSymbol('+', null, 20, (left, parser) => {
}
})
+newSymbol('-', null, 20, (left, parser) => {
+ return {
+ type: 'subtract',
+ left: left,
+ right: parser.expression(20)
+ }
+})
+
newSymbol('end', null, -1)
const newParser = (tokens) => {