# How to create a text side by side output in node.js (as a diff)
This actually was an interview question from VanHack (opens new window), a platform for remote digital work.
And here i explain my initial and naive approach.
By reading multiple file .txt
, create a text side by side that output text column like this.
Matsuo Bashô: Frog Haiku Matsuo Bashô: Frog Haiku
Translated by Kenneth Rexroth Translated by Tim Chilcott
An old pond — ancient is the pond —
The sound suddenly a frog leaps — now!
Of a diving frog. the water echoes
# Arguments
-s (width in character of horizontal text column ): Number
Default:
- longest row length per file
-c (number of column space characters): Number
Default
- 2 space characters
files: String
# Check params
-s and -c will be follow by a positive number
files will be given in any order
# Algorithm
Create a function for retrieveArguments
Function retrieveArguments
- read the arguments
- store all .txt extension filespath
- check for numbers
- identify previous element for -c & -s
Function getAllFilesContentPromises
- readline using createReadStream from one file
- transform line string to an arrayLine
- append arrayLine to an object
- add line lenght (width characters) to the object
Function getAllFilesContentPromise
- process the array of Promises from
getAllFilesContentPromises
Columnization ( Naive approach )
- While column counter is less than maxColumnSize,
- Go to each column per file,
- Search maxCharLengthFile
- add the padding on columns using maxCharLengthFile
- add the space character between columns
- add the fileLine to the arrayRow
- go to the next file
- did you reach to the last file?, append it to a hashtable and look the first file again
*only works with same column length files.
# Key concepts
# Node.js Buffers (opens new window)
A buffer is an area of memory.
A simple visualization of a buffer is when you are watching a YouTube video and the red line goes beyond your visualization point: you are downloading data faster than you're viewing it, and your browser buffers it.
In order words store data to be process later
# Node.js Stream (opens new window)
Traditionally, when you tell the program to read a file, the file is read into memory, from start to finish, and then you process it.
Using streams you read it piece by piece, processing its content without keeping it all in memory.
Streams provide two major advantages:
- Memory efficiency
- Time efficiency