index.js (2307B)
1 const fs = require('fs'); 2 const through = require('through2'); 3 const by_paragraph = require('../common/by-paragraph'); 4 const line_by_line = require('../common/line-for-line'); 5 6 String.prototype.startsWith = function(subject) { 7 return this.substr(0, subject.length) === subject; 8 }; 9 10 function verify(left, right) { 11 // If both values are 12 if ( 13 ('number' === typeof left) && 14 ('number' === typeof right) 15 ) { 16 if (left < right) return true; 17 if (left > right) return false; 18 } 19 // If both values are lists, compare values of each list 20 if ( 21 Array.isArray(left) && 22 Array.isArray(right) 23 ) { 24 const len = Math.max(left.length, right.length); 25 for(let i=0; i < len; i++) { 26 if ('undefined' === typeof left[i]) return true; 27 if ('undefined' === typeof right[i]) return false; 28 const result = verify(left[i], right[i]); 29 if ('boolean' === typeof result) return result; 30 } 31 } 32 // If exactly one value is an int, convert the integer to a list and retry 33 if ( 34 (Array.isArray(left)) && 35 ('number' === typeof right) 36 ) { 37 right = [right]; 38 return verify(left, right); 39 } 40 if ( 41 ('number' === typeof left) && 42 (Array.isArray(right)) 43 ) { 44 left = [left]; 45 return verify(left, right); 46 } 47 } 48 49 let pairs = 0; 50 let validSum = 0; 51 const dividerA = [[2]]; 52 const dividerB = [[6]]; 53 const packets = [ 54 dividerA, 55 dividerB, 56 ]; 57 58 fs.createReadStream('input') 59 .pipe(by_paragraph()) 60 61 // Minor parsing 62 .pipe(through.obj(function(paragraph, enc, cb) { 63 paragraph = paragraph.toString(); 64 this.push(paragraph.split('\n').map(line => JSON.parse(line))); 65 cb(); 66 })) 67 68 .pipe(through.obj(function(pair, enc, cb) { 69 const [left, right] = pair; 70 71 const valid = verify(left, right); 72 pairs++; 73 if (valid) validSum += pairs; 74 75 packets.push(left, right); 76 77 console.log(left); 78 console.log(right); 79 console.log(valid); 80 console.log(''); 81 82 cb(); 83 })) 84 85 .on('finish', () => { 86 87 packets.sort((left, right) => { 88 return verify(left, right) ? -1 : 1; 89 }); 90 const idxA = packets.indexOf(dividerA) + 1; 91 const idxB = packets.indexOf(dividerB) + 1; 92 const key = idxA * idxB; 93 94 console.log(packets); 95 console.log({ validSum, key }); 96 console.log('finish'); 97 });