Created
June 6, 2018 04:54
-
-
Save shaefer/d0754c5c9b7a5a37a0aaa20f3a3b4c2a to your computer and use it in GitHub Desktop.
DiceBag -> Phase 4 (extra credit 1)
This file contains 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
import {sum} from './ArrayUtils' | |
import seedrandom from 'seedrandom' | |
export const d6 = (generator = Math.random) => { | |
return rollDice(1, 6, generator); | |
} | |
export const rollDiceSets = (diceSets, generator = Math.random) => { | |
let setResults = []; | |
for(let i = 0;i<=(diceSets.length - 1);i++) { | |
const diceSet = diceSets[i]; | |
setResults.push(rollDice(diceSet.numOfDice, diceSet.numOfSides, generator)); | |
} | |
return { | |
total: sum(setResults.map(x => x.total)), | |
setResults: setResults | |
}; | |
} | |
export const rollDice = (numOfDice, numOfSides, generator = Math.random) => { | |
if (numOfDice > 100000) throw new Exception("Max dice of 10000 exceeded"); | |
if (numOfSides > 100000) throw new Exception("Max sides of 10000 exceeded"); | |
let individualResults = []; | |
for(let i = 1;i <= numOfDice;i++) { | |
const result = Math.floor(generator() * numOfSides) + 1; | |
individualResults.push(result); | |
} | |
return { | |
total: sum(individualResults), | |
individualResults: individualResults | |
}; | |
} | |
export const DiceBag = { | |
d6: d6, | |
rollDice: rollDice, | |
rollDiceSets: rollDiceSets | |
}; | |
export const DiceBagWithSeed = (seed) => { | |
const generator = new seedrandom(seed); | |
return { | |
d6: () => { | |
return d6(generator); | |
}, | |
rollDice: (numOfDice, numOfSides) => { | |
return rollDice(numOfDice, numOfSides, generator); | |
}, | |
rollDiceSets: (diceSets) => { | |
return rollDiceSets(diceSets, generator); | |
} | |
} | |
} | |
export default DiceBag; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment