11/**
22 * Generates a checksum for a string by concatenating
33 * 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
55 */
66const 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
88 let result = ''
99 if ( parsed . length === 1 ) { // some strings only have a single digit
1010 result = `${ parsed } ${ parsed } `
@@ -16,12 +16,22 @@ const checksumLine = (data) => {
1616
1717/**
1818 * Generates the checksum for an entire set
19- * @param Arrray of lines containing data
19+ * @param { array } set of lines containing data
2020 */
2121const checksumSet = ( set ) => {
2222 return set . reduce ( ( total , current ) => {
23- return total + checksumLine ( current )
23+ return total + checksumLine ( sanitizeLine ( current ) )
2424 } , 0 )
2525}
2626
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