Skip to content

Instantly share code, notes, and snippets.

@andrewgremlich
Created April 26, 2022 17:24
Show Gist options
  • Save andrewgremlich/f50a34f83e9602a582ea74aa3567e506 to your computer and use it in GitHub Desktop.
Save andrewgremlich/f50a34f83e9602a582ea74aa3567e506 to your computer and use it in GitHub Desktop.
The Phonebook (JS style)
const fs = require("fs");
const contactsReadStream = fs.createReadStream("./contacts.txt", {
encoding: "utf8",
});
contactsReadStream.on("data", (data) => {
const phonebook = {};
let output = "";
data.split("\n").map((line) => {
const trimmedLine = line.trim();
const split = trimmedLine.split(" ");
const hasNumber = split.length === 2;
if (hasNumber) {
phonebook[split[0]] = split[1];
} else {
if (phonebook[split[0]]) {
output = `${output}\n${split[0]}=${phonebook[split[0]]}`;
} else {
output = `${output}\nNot Found.`
}
}
});
console.log(output);
});
const fs = require("fs");
const contactsReadStream = fs.createReadStream('./contacts.txt', {encoding: 'utf8'})
contactsReadStream.on("data", (data) => {
const phonebook = {};
const [boundary, ...contactInfo] = data.split("\n").map((line) => line.trim());
let i = 0;
while (i < +boundary) {
const [name, number] = contactInfo[i].split(" ");
phonebook[name] = number;
i++;
}
const lookupCollection = contactInfo.slice(+boundary);
let output = "";
for (let lookupName of lookupCollection) {
if (phonebook[lookupName]) {
output = output + `\n${lookupName}=${phonebook[lookupName]}`
} else {
output = output + "\nNot found";
}
}
console.log(output);
})
@andrewgremlich
Copy link
Author

What if they are all inter-mingled?

@andrewgremlich
Copy link
Author

What if it was a really huge file where the stream could only do parts at a time?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment