index.js (1796B)
1 const fs = require('fs'); 2 const through = require('through2'); 3 const line_by_line = require('../common/line-for-line'); 4 const nerdamer = require('nerdamer/all.min'); 5 6 const step1 = {}; 7 const step2 = { equation: '', subst: {'humn':'x'} }; 8 9 // fs.createReadStream('sample') 10 fs.createReadStream('input') 11 .pipe(line_by_line()) 12 13 // Minor parsing 14 .pipe(through.obj(function(line, enc, cb) { 15 line = line.toString(); 16 17 const [id, definition] = line.split(':').map(s => s.trim()); 18 19 // Number = assign directly 20 if (!isNaN(definition)) { 21 step1[id] = () => parseInt(definition); 22 if (id !== 'humn') step2.subst[id] = definition; 23 return cb(); 24 } 25 26 // Split & track substitution 27 step2.subst[id] = definition; 28 let [left, operation, right] = definition.split(' '); 29 30 if (id == 'root') { 31 step2.equation = `${left} = ${right}`; 32 } 33 34 step1[id] = () => { 35 if (!right) return step1[left](); 36 const l = step1[left](); 37 const r = step1[right](); 38 switch(operation) { 39 case '+': return l + r; 40 case '-': return l - r; 41 case '/': return l / r; 42 case '*': return l * r; 43 } 44 }; 45 46 cb(); 47 })) 48 49 .on('finish', () => { 50 console.log('loaded'); 51 52 // First do step 1 53 const step1_result = step1.root(); 54 55 // Expand step2 equation 56 let replaced; 57 do { 58 replaced = false; 59 for(const [token,op] of Object.entries(step2.subst)) { 60 if (~step2.equation.indexOf(token)) { 61 replaced = true; 62 step2.equation = step2.equation.replace(`${token}`, `(${op})`); 63 } 64 } 65 } while(replaced); 66 67 const solved = nerdamer.solveEquations(step2.equation, 'x'); 68 69 console.log({ step1: step1_result, step2: solved.toString() }); 70 });