diff --git a/lib/BattlePlan.js b/lib/BattlePlan.js index abfda09..a02ac45 100644 --- a/lib/BattlePlan.js +++ b/lib/BattlePlan.js @@ -3,6 +3,8 @@ module.exports = class BattlePlan { constructor(opts) { + validateOptions(opts) + this.allocations = opts.allocations this.name = opts.name this.author = opts.author @@ -37,3 +39,16 @@ module.exports = class BattlePlan { } } } + +function validateOptions(opts) { + if (!Array.isArray(opts.allocations)) { + throw new Error("a new BattlePlan's 'allocations' option must be an array") + } + if (opts.allocations.length !== 10) { + throw new Error(`A BattlePlan must allocate armies to exactly 10 castles, not ${opts.allocations.length}`) + } + const allocationSum = opts.allocations.reduce((acc, val) => acc + val, 0) + if (allocationSum !== 100) { + throw new Error(`A BattlePlan must allocate exactly 100 armies, not ${allocationSum}`) + } +} diff --git a/lib/BattlePlanSpec.js b/lib/BattlePlanSpec.js index 2dab06c..2adc3ca 100644 --- a/lib/BattlePlanSpec.js +++ b/lib/BattlePlanSpec.js @@ -18,6 +18,39 @@ test('BattlePlan(opts) sets properties from options', function* (t) { t.is(myPlan.author, 'Genghis Khan') }) +test('throws an Error if opts.allocations is not an Array', function* (t) { + const err = t.throws(() => { + new BattlePlan({ // eslint-disable-line no-new + allocations: null, + name: 'test-plan', + author: 'Genghis Khan' + }) + }) + t.is(err.message, "a new BattlePlan's 'allocations' option must be an array") +}) + +test('allocations must include exactly 10 castles', function* (t) { + const err = t.throws(() => { + new BattlePlan({ // eslint-disable-line no-new + allocations: [20, 20, 20, 20, 20], + name: 'test-plan', + author: 'Genghis Khan' + }) + }) + t.is(err.message, 'A BattlePlan must allocate armies to exactly 10 castles, not 5') +}) + +test('allocations must total exactly 100', function* (t) { + const err = t.throws(() => { + new BattlePlan({ // eslint-disable-line no-new + allocations: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + name: 'test-plan', + author: 'Genghis Khan' + }) + }) + t.is(err.message, 'A BattlePlan must allocate exactly 100 armies, not 10') +}) + test('.fight(opponent) returns `win` when the first plan wins', function* (t) { t.is(samples.allToCastleTen.fight(samples.allToCastleOne), 'win') })