Skip to content

Commit

Permalink
Fixed parsing issue, added more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevin-DDR committed Oct 18, 2024
1 parent 2905892 commit a37da96
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "kd20",
"version": "0.3.6",
"version": "0.3.7",
"description": "A simple dice roller that can handle complex die sequences",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
Expand Down
19 changes: 13 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,23 @@ export const parse = (s: string): ParsedBlock[] => {
cell = cell.toLowerCase()
cell = cell.replaceAll('(plus)', '+').replaceAll('(minus)', '-')
if (cell.includes('d')) {
const tmp = cell.split('d')
if(isNaN(+tmp[0]) || isNaN(+tmp[1])) throw new ParsingError(cell)
const isNegative = tmp[0][0] === '-'
if(cell[0] === 'd') cell = '1' + cell
const splitString = cell.split('d')
if(
isNaN(+splitString[0]) ||
isNaN(+splitString[1]) ||
splitString.length !== 2 ||
splitString[0] === '' ||
splitString[1] === ''
) throw new ParsingError(cell)
const isNegative = splitString[0][0] === '-'
if (isNegative) {
tmp[0] = tmp[0].substring(1)
splitString[0] = splitString[0].substring(1)
}
for (let i = 0; i < parseInt(tmp[0]); i++) {
for (let i = 0; i < parseInt(splitString[0]); i++) {
res.push({
type: 'die',
maxValue: parseInt(tmp[1]),
maxValue: parseInt(splitString[1]),
negative: isNegative
})
}
Expand Down
11 changes: 11 additions & 0 deletions tests/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ test('Parse a negative value or die correctly', () => {
expect(result2).toEqual([{ type: 'fixed', maxValue: -3 }])
})

test('Parse d20 (implicit 1d20)', () => {
const result = parse('d20')
expect(result).toEqual([{ type: 'die', maxValue: 20, negative: false }])
})

test('Parse a complex string', () => {
const result = parse('3d6 + 1d4 - 5 - 2d4 + 1')
expect(result).toEqual([
Expand All @@ -37,5 +42,11 @@ test('Throw an exception for an invalid string', () => {
expect(() => parse('+f')).toThrow(ParsingError)
expect(() => parse('3dz')).toThrow(ParsingError)
expect(() => parse('4d4sss')).toThrow(ParsingError)
expect(() => parse('dd20')).toThrow(ParsingError)
expect(() => parse('2dd20')).toThrow(ParsingError)
expect(() => parse('2d')).toThrow(ParsingError)
expect(() => parse('2dd')).toThrow(ParsingError)
expect(() => parse('2d 2d')).toThrow(ParsingError)
expect(() => parse('d1d4')).toThrow(ParsingError)
})

0 comments on commit a37da96

Please sign in to comment.