Skip to content

Instantly share code, notes, and snippets.

@niaeashes
Last active January 21, 2021 15:51
Show Gist options
  • Save niaeashes/6475ab35da76945e08c83a9a690b2560 to your computer and use it in GitHub Desktop.
Save niaeashes/6475ab35da76945e08c83a9a690b2560 to your computer and use it in GitHub Desktop.
diceroll.ts
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 + '" }')()
}
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