-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
63 lines (54 loc) · 1.76 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { coreNotationPattern } from '../../constants/regexp'
import { dieFactory } from '../../Die'
import { isCustomSides } from '../../Die/guards'
import { CoreRollArgument, RollArgument } from '../../types/argument'
import { DicePoolOptions } from '../../types/options'
import { DicePoolParameters, RollParameters } from '../../types/parameters'
import { DiceNotation } from '../../types/primitives'
import parseNotation from './parse-notation'
const isDicePoolOptions = (
argument: unknown
): argument is DicePoolOptions<number> | DicePoolOptions<string> =>
typeof argument === 'object' &&
(argument as DicePoolOptions<number> | DicePoolOptions<string>).sides !==
undefined
export const isDiceNotation = (
argument: unknown
): argument is DiceNotation<number> | DiceNotation<string> =>
!!coreNotationPattern.test(String(argument))
function parseDiceOptions(
options: CoreRollArgument | undefined
): DicePoolOptions<string | number> {
if (isDicePoolOptions(options)) {
return options
}
if (isDiceNotation(options)) {
return parseNotation(options)
}
return {
quantity: 1,
sides: isCustomSides(options) ? options.map(String) : Number(options)
}
}
function parseArgument(
argument: CoreRollArgument | undefined
): RollParameters['dicePools'] {
const id = crypto.randomUUID()
const options = parseDiceOptions(argument)
return {
[id]: {
options,
argument,
die: dieFactory(options.sides)
} as DicePoolParameters<number> | DicePoolParameters<string>
}
}
function parseArguments(argument: RollArgument | undefined): RollParameters {
const args = [argument].flat()
const dicePools = args.reduce(
(acc, arg) => ({ ...acc, ...parseArgument(arg) }),
{}
)
return { dicePools }
}
export default parseArguments