The Phonebook (JS style)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}) | |
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
What if they are all inter-mingled?