Skip to content

Commit

Permalink
adds validations for allocations in a BattlePlan's constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
Evan Cowden committed Feb 19, 2017
1 parent 0634853 commit 134a572
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/BattlePlan.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
module.exports = class BattlePlan {

constructor(opts) {
validateOptions(opts)

this.allocations = opts.allocations
this.name = opts.name
this.author = opts.author
Expand Down Expand Up @@ -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}`)
}
}
33 changes: 33 additions & 0 deletions lib/BattlePlanSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
Expand Down

0 comments on commit 134a572

Please sign in to comment.