diff options
author | Marcin Chrzanowski <marcin.j.chrzanowski@gmail.com> | 2017-07-10 14:04:45 -0400 |
---|---|---|
committer | Marcin Chrzanowski <marcin.j.chrzanowski@gmail.com> | 2017-07-10 14:46:59 -0400 |
commit | 8cb2f0e3b007d64e91648d732741c1b0371407fb (patch) | |
tree | 4c3b7e7aa482e902a5e673a0ed3dbe5d1508d0f9 | |
parent | b170693c5d8e73286f38e499a0ba91ee9bafa1bb (diff) |
Implement die addition
-rw-r--r-- | __tests__/dice.test.js | 48 | ||||
-rw-r--r-- | src/dice.js | 7 |
2 files changed, 54 insertions, 1 deletions
diff --git a/__tests__/dice.test.js b/__tests__/dice.test.js index 45c859b..275e0a9 100644 --- a/__tests__/dice.test.js +++ b/__tests__/dice.test.js @@ -1,4 +1,4 @@ -const { d } = require('../src/dice.js') +const { d, add } = require('../src/dice.js') const defaultNumberRolls = 500 @@ -128,6 +128,29 @@ const basicDieTestSpecs = (number, sides) => { } } } + +const combinedDiceTestSpecs = (dieSpecs) => { + const individualTestSpecs = + dieSpecs.map(spec => (basicDieTestSpecs(spec.number, spec.sides))) + + const combineSpecField = (fieldGetter) => { + return individualTestSpecs.reduce((total, spec) => { + return total + fieldGetter(spec) + }, 0) + } + + return { + diceCount: combineSpecField(spec => (spec.diceCount)), + average: { + average: combineSpecField(spec => (spec.average.average)) + }, + variance: { + variance: combineSpecField(spec => (spec.variance.variance)) + }, + bounds: { + low: combineSpecField(spec => (spec.bounds.low)), + high: combineSpecField(spec => (spec.bounds.high)), + } } } @@ -138,8 +161,31 @@ const describeBasicDie = (number, sides, numberRolls = defaultNumberRolls) => { }) } +const describeCompoundDice = (diceSpecs, numberRolls = defaultNumberRolls) => { + const dieString = diceSpecs.reduce((string, spec, index) => ( + string + `${spec.number}d${spec.sides}` + + (index < diceSpecs.length - 1 ? ' + ' : '') + ), '') + + const die = diceSpecs.slice(1).reduce((die, spec) => { + return add(die, d(spec.number, spec.sides)) + }, d(diceSpecs[0].number, diceSpecs[0].sides)) + + describe(dieString, () => testDie(die, combinedDiceTestSpecs(diceSpecs), + numberRolls)) +} + describe('basic dice', () => { describeBasicDie(1, 6) describeBasicDie(2, 8, 500) describeBasicDie(20, 1) }) + +describe('add', () => { + describeCompoundDice([ { number: 1, sides: 6 }, { number: 1, sides: 4 } ]) + describeCompoundDice([ + { number: 3, sides: 6 }, + { number: 2, sides: 8 }, + { number: 1, sides: 1 } + ]) +}) diff --git a/src/dice.js b/src/dice.js index 2914317..bc75cb7 100644 --- a/src/dice.js +++ b/src/dice.js @@ -10,9 +10,16 @@ const d = (number, sides) => { } } +const add = (die1, die2) => { + return () => { + return die1().concat(die2()) + } +} + const roll = (die) => { return die().reduce((a, b) => (a + b)) } exports.d = d +exports.add = add exports.roll = roll |