Skip to content

Commit bb1df5d

Browse files
feat(2023-01): calculate checksums for trebuchet data
1 parent e436ac3 commit bb1df5d

File tree

5 files changed

+1015
-7
lines changed

5 files changed

+1015
-7
lines changed

2023/day-01/checksum.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,14 @@
44
* @param string containing a single line of data
55
*/
66
const checksumLine = (data) => {
7-
data.replace(/([^0-9])+/g, '') // trim non-numeric characters
8-
const checksumString = `${data[0]}${data[-1]}`
9-
return parseInt(checksumString)
7+
const parsed = data.replace(/([^0-9])/g, '') // trim non-numeric characters
8+
let result = ''
9+
if (parsed.length === 1) { // some strings only have a single digit
10+
result = `${parsed}${parsed}`
11+
} else {
12+
result = `${parsed[0]}${parsed[parsed.length - 1]}`
13+
}
14+
return parseInt(result)
1015
}
1116

1217
/**

2023/day-01/checksum.test.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@ describe('--- Day 1: Trebuchet?! ---', () => {
88
it('calculates the checksum for a string by concatentating the first and last number', () => {
99
// provided
1010
expect(checksumLine('1abc2')).to.equal(12)
11-
expect(checksumLine('pqr3stu8vwx')).to.equal(18)
11+
expect(checksumLine('pqr3stu8vwx')).to.equal(38)
1212
expect(checksumLine('a1b2c3d4e5f')).to.equal(15)
13+
})
14+
it('handles the edge case of a line with only a single digit', () => {
15+
// provided
1316
expect(checksumLine('treb7uchet')).to.equal(77)
1417
})
1518
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy