Skip to content

Commit 428da57

Browse files
perf(2020-day-07): optimize bag search
1 parent a78fc2f commit 428da57

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

2020/day-7/bagRules.js

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,27 +22,32 @@ const parseRule = (rule) => {
2222
}
2323

2424
const findAllowedOuter = (rules, color) => {
25-
const allowed = {}
26-
27-
// Loop through the rules, find all colors this bag is allowed within
28-
rules.filter((rule) => {
29-
if (!rule.inner) { return false }
30-
// match when inners contain the color
25+
const isAllowed = (rule) => {
26+
if (!rule.inner) return false
3127
return (
3228
rule.inner.filter((child) => {
33-
return (child.color === color)
29+
return (
30+
child.color === color
31+
)
3432
}).length > 0
3533
)
36-
}).forEach((rule) => {
34+
}
35+
36+
const allowed = {}
37+
38+
// Loop through the rules, find all colors this bag is allowed within
39+
rules.filter(isAllowed).forEach((rule) => {
3740
allowed[rule.outer] = true
3841
})
3942

4043
// Take the list of allowed colors, and find out which they are allowed within
4144
Object.keys(allowed).forEach((color) => {
42-
// Recursively loop
43-
Object.assign(allowed, findAllowedOuter(rules, color))
45+
const temp = findAllowedOuter(rules, color)
46+
if (Object.keys(temp).length > 0) {
47+
Object.assign(allowed, temp)
48+
}
4449
})
45-
50+
console.log(allowed)
4651
return allowed
4752
}
4853

0 commit comments

Comments
 (0)