Skip to content

Commit a623438

Browse files
feat[2020-day-01]: find matching expenses in expense report
Finds matching expenses in an array matching a checksum
1 parent 506474d commit a623438

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

2020/day-01/expenseValidation.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
/**
3+
* Validates a list of records by comparing every combination
4+
* to the checksum. Stops when the first match is found
5+
*/
6+
const validateRecords = (records, checksum = 2020) => {
7+
const results = []
8+
9+
// We're using Array.find() at each level so it stops looping
10+
// onced matched. This game has a habit of throwing huge
11+
// data sets to discourage brute-forcing
12+
const matcher = records.find((record) => {
13+
const match = records.find(matchRec => record + matchRec === checksum)
14+
if (match) {
15+
results.push(match)
16+
return true
17+
}
18+
return false
19+
})
20+
if (matcher) {
21+
results.push(matcher)
22+
}
23+
24+
if (results.length < 2) {
25+
throw new Error('Couldn\'t find a checksum match')
26+
}
27+
return results
28+
}
29+
30+
module.exports = {
31+
validateRecords
32+
}

0 commit comments

Comments
 (0)