diff options
author | Marcin Chrzanowski <marcin.j.chrzanowski@gmail.com> | 2017-08-23 20:19:52 -0400 |
---|---|---|
committer | Marcin Chrzanowski <marcin.j.chrzanowski@gmail.com> | 2017-08-23 20:19:52 -0400 |
commit | d6051158e52db719ae506fc48a45d22975b16a8b (patch) | |
tree | 43e16f3fe4e75bc48b99127cd834c1d74e0bf860 | |
parent | 6a323b30b3a4b80baec963b4308bd8d8d2a48ad9 (diff) |
Implement again
-rw-r--r-- | __tests__/dice.test.js | 28 | ||||
-rw-r--r-- | src/dice.js | 38 |
2 files changed, 65 insertions, 1 deletions
diff --git a/__tests__/dice.test.js b/__tests__/dice.test.js index 15941cb..a18584c 100644 --- a/__tests__/dice.test.js +++ b/__tests__/dice.test.js @@ -9,7 +9,8 @@ const { negative, explode, keepHigh, - keepLow + keepLow, + again } = require('../src/dice.js') const defaultNumberRolls = 500 @@ -534,3 +535,28 @@ describe('keep', () => { testDie(die, basicDieTestSpecs(1, 20)) }) }) + +describe('again', () => { + describe('10A1d10', () => { + const die = again(constant(10), d(constant(1), constant(10))) + + testDie(die, { + variableDiceCount: { + min: 1, + max: Infinity + }, + average: { + average: 6.11 + }, + variance: { + variance: 19.03 + }, + bounds: { + low: 1, + high: Infinity, + expectLow: true, + expectHigh: false + } + }) + }) +}) diff --git a/src/dice.js b/src/dice.js index 6f3b7da..ef67edf 100644 --- a/src/dice.js +++ b/src/dice.js @@ -111,6 +111,43 @@ const keepLow = (die1, die2) => { } } +const again = (die1, die2) => { + return () => { + const againOn = roll(die1) + let rolls = [] + let rollAgain = [] + + const rollDie = (die) => { + const roll = die() + + if (roll >= againOn) { + rollAgain.push(die) + } + + let returnedOriginal = false + rolls.push(() => { + if (!returnedOriginal) { + returnedOriginal = true + return roll + } else { + return die() + } + }) + } + + die2().forEach(rollDie) + + while (rollAgain.length > 0) { + const oldRollAgain = rollAgain + rollAgain = [] + oldRollAgain.forEach(rollDie) + } + + return rolls + } +} + + exports.pool = pool exports.roll = roll exports.constant = constant @@ -123,3 +160,4 @@ exports.negative = negative exports.explode = explode exports.keepHigh = keepHigh exports.keepLow = keepLow +exports.again = again |