Skip to content

Commit 8ec6621

Browse files
feat(2020-day-07): parse a bag rule into an addressable object
1 parent 5884017 commit 8ec6621

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

2020/day-7/bagRules.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const parseRule = (rule) => {
2+
const result = {}
3+
// Get the color of the outer bag
4+
const outRemainder = rule.split(' contain ')
5+
result.outer = outRemainder.shift().replace('bags', 'bag')
6+
// Get the color and values of inner bags
7+
if (outRemainder[0] !== 'no other bags.') {
8+
result.inner = outRemainder[0].split(', ').map((str) => {
9+
const inRemainder = str.split(' ')
10+
const count = Number(inRemainder.shift())
11+
const color = inRemainder.join(' ').replace('s.', '')
12+
return {
13+
count,
14+
color
15+
}
16+
})
17+
}
18+
19+
return result
20+
}
21+
22+
module.exports = {
23+
parseRule
24+
}

2020/day-7/bagRules.test.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/* eslint-env mocha */
2+
const { expect } = require('chai')
3+
const { parseRule } = require('./bagRules')
4+
5+
const testData = {
6+
rules: [
7+
'light red bags contain 1 bright white bag, 2 muted yellow bags.',
8+
'dark orange bags contain 3 bright white bags, 4 muted yellow bags.',
9+
'bright white bags contain 1 shiny gold bag.',
10+
'muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.',
11+
'shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.',
12+
'dark olive bags contain 3 faded blue bags, 4 dotted black bags.',
13+
'vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.',
14+
'faded blue bags contain no other bags.',
15+
'dotted black bags contain no other bags.'
16+
]
17+
}
18+
19+
describe('--- Day 7: Handy Haversacks ---', () => {
20+
describe('Part 1', () => {
21+
describe('parseRule()', () => {
22+
it('converts a natural language rule into a useable object', () => {
23+
expect(parseRule(testData.rules[0])).to.deep.equal({
24+
outer: 'light red bag',
25+
inner: [
26+
{
27+
count: 1,
28+
color: 'bright white bag'
29+
}, {
30+
count: 2,
31+
color: 'muted yellow bag'
32+
}
33+
]
34+
})
35+
})
36+
it('handles bags that do not accept children', () => {
37+
expect(parseRule(testData.rules[7])).to.deep.equal({
38+
outer: 'faded blue bag'
39+
})
40+
})
41+
})
42+
})
43+
})

0 commit comments

Comments
 (0)