1
1
/**
2
2
* Generates a checksum for a string by concatenating
3
3
* the first and last digits found in the string
4
- * @param string containing a single line of data
4
+ * @param { string } data of a single line
5
5
*/
6
6
const checksumLine = ( data ) => {
7
- const parsed = data . replace ( / ( [ ^ 0 - 9 ] ) / g, '' ) // trim non-numeric characters
7
+ const parsed = data . replaceAll ( / ( [ ^ 0 - 9 ] ) / g, '' ) // trim non-numeric characters
8
8
let result = ''
9
9
if ( parsed . length === 1 ) { // some strings only have a single digit
10
10
result = `${ parsed } ${ parsed } `
@@ -16,12 +16,22 @@ const checksumLine = (data) => {
16
16
17
17
/**
18
18
* Generates the checksum for an entire set
19
- * @param Arrray of lines containing data
19
+ * @param { array } set of lines containing data
20
20
*/
21
21
const checksumSet = ( set ) => {
22
22
return set . reduce ( ( total , current ) => {
23
- return total + checksumLine ( current )
23
+ return total + checksumLine ( sanitizeLine ( current ) )
24
24
} , 0 )
25
25
}
26
26
27
- module . exports = { checksumLine, checksumSet }
27
+ const numbers = [ 'zero' , 'one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' , 'eight' , 'nine' ]
28
+ const reg = new RegExp ( numbers . join ( '|' ) , 'g' )
29
+ /**
30
+ * Sanitzizes a line by replacing spelled-out numbers with data
31
+ * @param {string } data line of input to sanitize
32
+ */
33
+ const sanitizeLine = ( data ) => {
34
+ return data . replaceAll ( reg , ( matched ) => numbers . indexOf ( matched ) )
35
+ }
36
+
37
+ module . exports = { checksumLine, checksumSet, sanitizeLine }
0 commit comments