|
| 1 | +const fs = require('fs'); |
| 2 | +const readline = require('readline'); |
| 3 | + |
| 4 | +if (process.argv.length !== 4) { |
| 5 | + throw new Error(`Usage: node ${process.argv[1]} [file A] [file B]`); |
| 6 | +} |
| 7 | + |
| 8 | +const EPSILON = 1e-9; |
| 9 | + |
| 10 | +const isFuzzyEqual = (a, b) => { |
| 11 | + if (typeof a === 'number' && typeof b === 'number') { |
| 12 | + return (isNaN(a) && isNaN(b)) || Math.abs(a - b) < EPSILON; |
| 13 | + } else if (typeof a === 'object' && typeof b === 'object') { |
| 14 | + for (key in a) { |
| 15 | + if (!isFuzzyEqual(a[key], b[key])) { |
| 16 | + return false; |
| 17 | + } |
| 18 | + } |
| 19 | + for (key in b) { |
| 20 | + if (!isFuzzyEqual(a[key], b[key])) { |
| 21 | + return false; |
| 22 | + } |
| 23 | + } |
| 24 | + return true; |
| 25 | + } else { |
| 26 | + return a === b; |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +const cmpLines = (index, a, b) => { |
| 31 | + if (!isFuzzyEqual(a, b)) { |
| 32 | + a && console.log('\x1b[31m%s\x1b[0m', `${index}: - ${JSON.stringify(a)}`); |
| 33 | + b && console.log('\x1b[32m%s\x1b[0m', `${index}: + ${JSON.stringify(b)}`); |
| 34 | + process.exitCode = 1; |
| 35 | + } |
| 36 | +}; |
| 37 | + |
| 38 | +const lines = [[], []]; |
| 39 | +const filePromises = [process.argv[2], process.argv[3]].map( |
| 40 | + (filename, fileIndex) => { |
| 41 | + const rl = readline.createInterface({ |
| 42 | + input: fs.createReadStream(filename), |
| 43 | + terminal: false, |
| 44 | + }); |
| 45 | + |
| 46 | + let lineIndex = 0; |
| 47 | + rl.on('line', (line) => { |
| 48 | + const data = JSON.parse(line); |
| 49 | + lines[fileIndex][lineIndex] = data; |
| 50 | + if (lines[1 - fileIndex].length > lineIndex) { |
| 51 | + cmpLines(lineIndex, lines[0][lineIndex], lines[1][lineIndex]); |
| 52 | + } |
| 53 | + |
| 54 | + lineIndex++; |
| 55 | + }); |
| 56 | + |
| 57 | + return new Promise((resolve) => rl.on('close', resolve)); |
| 58 | + }, |
| 59 | +); |
| 60 | + |
| 61 | +Promise.all(filePromises).then(() => { |
| 62 | + const min = Math.min(lines[0].length, lines[1].length); |
| 63 | + const max = Math.max(lines[0].length, lines[1].length); |
| 64 | + for (let i = min; i < max; i++) { |
| 65 | + cmpLines(i, lines[0][i], lines[1][i]); |
| 66 | + } |
| 67 | +}); |
0 commit comments