Last active
January 21, 2021 15:51
-
-
Save niaeashes/6475ab35da76945e08c83a9a690b2560 to your computer and use it in GitHub Desktop.
diceroll.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const rollSingle = (face: number, rolled: number[]): number => { | |
const r = Math.ceil(Math.random() * face) | |
rolled.push(r) | |
return r | |
} | |
const roll = (count: number, face: number, rolled: number[]): number => [...Array(count)].reduce(r => r + rollSingle(face, rolled), 0) | |
globalThis.roll = roll | |
interface IDiceResult { | |
rolled: number[] | |
sum: number | |
} | |
const dice = (exp: string): IDiceResult => { | |
if (!exp.match(/^[\d\+\-\*\/\(\)D]+$/i)) { return { sum: 0, rolled: [] } } | |
return new Function('"use strict"; const rolled = []; const sum = ' + exp | |
.replace(/(\d+)?D(\d+)/ig, (code, c, f) => `roll(${c||'1'},${f}, rolled)`) + '; return { sum, rolled, exp: "' + exp + '" }')() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare var roll: (count: number, face: number, rolled: number[]) => number |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment