re: AoC Day 1: Chronal Calibration VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Node.js First, I created an async generator that read the input file stream chunk by chunk and yield each number line by line. async function*...
 

I also did mine in JS but I decided to use the readline interface to read each line individually and spend less memory by not loading the entire file in the memory at once.

I haven't trying using for await (... of ...) with the readline interface. Maybe I'll try that next. If anyone would like to try it please post it here.

Here are my solutions:

My solution in JavaScript / Node 11, using the readline interface:

readLines.js

const fs = require('fs');
const readline = require('readline');

const readLines = (file, onLine) => {
    const reader = readline.createInterface({
        input: fs.createReadStream(file),
        crlfDelay: Infinity
    });

    reader.on('line', onLine);

    return new Promise(resolve => reader.on('close', resolve));
};

const readFile = async file => {
    const lines = [];
    await readLines(file, line => lines.push(line));  
    return lines;
}

module.exports = {
    readLines,
    readFile
};

01a.js

const { readFile } = require('./readLines');

(async () => {
    const lines = await readFile('01-input.txt');

    const frequency = lines.reduce((frequency, line) => frequency + Number(line), 0);

    console.log(`The final frequency is ${frequency}`);
})();

01b.js

const { readFile } = require('./readLines');

(async () => {
    const lines = await readFile('01-input.txt');

    const frequencySet = new Set();

    let frequency = 0;
    let didAFrequencyReachTwice = false;

    while (!didAFrequencyReachTwice) {
        for (let line of lines) {
            frequency += Number(line);
            if (frequencySet.has(frequency)) {
                didAFrequencyReachTwice = true;
                break;
            }
            else {
                frequencySet.add(frequency);
            }
        }
    }

    console.log(`The first frequency reached twice is ${frequency}`);
})();
 

Readline doesn't work with async iterators and for await yet, but it just landed in 11.x staging.

Once it is released, my streamToFrequencies generator won't be needed.

Also, createReadStream only reads the file in 256 byte chunks at a time (or whatever you set the highwatermark to be, it does not read the entire file into memory. readFile would, however.

To read more about async iterators and generators and the for await syntax, check out 2ality.com/2018/04/async-iter-node...

code of conduct - report abuse