Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions src/cli/interactive.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,45 @@
import readline from "node:readline";

const interactive = () => {
// Write your code here
// Use readline module for interactive CLI
// Support commands: uptime, cwd, date, exit
// Handle Ctrl+C and unknown commands
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: "> ",
});

rl.prompt();

rl.on("line", (input) => {
const command = input.trim();

switch (command) {
case "uptime":
console.log(`Uptime: ${process.uptime().toFixed(2)}s`);
break;

case "cwd":
console.log(process.cwd());
break;

case "date":
console.log(new Date().toISOString());
break;

case "exit":
console.log("Goodbye!");
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can write here rl.close() to reuse logic of closing the application.

process.exit(0);

default:
console.log("Unknown command");
}

rl.prompt();
});

rl.on("close", () => {
console.log("Goodbye!");
process.exit(0);
});
};

interactive();
47 changes: 43 additions & 4 deletions src/cli/progress.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,47 @@
const progress = () => {
// Write your code here
// Simulate progress bar from 0% to 100% over ~5 seconds
// Update in place using \r every 100ms
// Format: [████████████████████ ] 67%
const args = process.argv.slice(2);
const getArg = (cliOption, defaultValue) => {
const index = args.indexOf(cliOption);
return index !== -1 ? args[index + 1] : defaultValue;
};

const duration = parseInt(getArg("--duration", 5000));
const interval = parseInt(getArg("--interval", 100));
const barLength = parseInt(getArg("--length", 30));
const rawColor = getArg("--color", null);

let colorStart = "";
const colorEnd = "\x1b[0m";
const cleanHex = rawColor.trim().replace("#", "");

if (/^[0-9A-Fa-f]{6}$/.test(cleanHex)) {
const r = parseInt(cleanHex.slice(0, 2), 16);
const g = parseInt(cleanHex.slice(2, 4), 16);
const b = parseInt(cleanHex.slice(4, 6), 16);
colorStart = `\x1b[38;2;${r};${g};${b}m`;
}

const startTime = Date.now();

const timer = setInterval(() => {
const now = Date.now();
const msPassed = now - startTime;
const percentRaw = Math.min(msPassed / duration, 1);

const filledCount = Math.floor(percentRaw * barLength);
const emptyCount = barLength - filledCount;
const displayPercent = Math.floor(percentRaw * 100);

const filledPart = `${colorStart}${"█".repeat(filledCount)}${colorEnd}`;
const emptyPart = " ".repeat(emptyCount);

process.stdout.write(`\r[${filledPart}${emptyPart}] ${displayPercent}%`);

if (percentRaw >= 1) {
clearInterval(timer);
process.stdout.write("\nDone!\n");
}
}, interval);
};

progress();
19 changes: 13 additions & 6 deletions src/cp/execCommand.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import {spawn} from "child_process";
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's better import built-in modules with 'node:' prefix.
https://nodejs.org/dist/latest-v22.x/docs/api/esm.html#node-imports


const execCommand = () => {
// Write your code here
// Take command from CLI argument
// Spawn child process
// Pipe child stdout/stderr to parent stdout/stderr
// Pass environment variables
// Exit with same code as child
const commandString = process.argv[2];

const child = spawn(commandString, {
stdio: "inherit",
env: process.env,
shell: true,
});

child.on("exit", (code) => {
process.exit(code);
});
};

execCommand();
27 changes: 23 additions & 4 deletions src/hash/verify.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
import fs from "fs";
import {createHash} from "crypto";
import path from "path";

const verify = async () => {
// Write your code here
// Read checksums.json
// Calculate SHA256 hash using Streams API
// Print result: filename — OK/FAIL
const checksumsPath = path.resolve("./src/hash/checksums.json");
const checksumsData = await fs.promises.readFile(checksumsPath, "utf8");
const checksums = JSON.parse(checksumsData);

const dir = path.dirname(checksumsPath);

for (const [fileName, expectedHash] of Object.entries(checksums)) {
const absolutePath = path.resolve(dir, fileName);

try {
const fileBuffer = await fs.promises.readFile(absolutePath);
const actualHash = createHash("sha256").update(fileBuffer).digest("hex");
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In assignment it's required to calculate hash using Streams API.

console.log(
`${fileName} — ${actualHash === expectedHash ? "OK" : "FAIL"}`,
);
} catch (err) {
console.log(`${fileName} — FAIL`);
}
}
};

await verify();
14 changes: 9 additions & 5 deletions src/modules/dynamic.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
const dynamic = async () => {
// Write your code here
// Accept plugin name as CLI argument
// Dynamically import plugin from plugins/ directory
// Call run() function and print result
// Handle missing plugin case
const pluginName = process.argv[2];
try {
const plugin = await import(`./plugins/${pluginName}.js`);
const resultString = plugin.run();
console.log(resultString);
} catch (error) {
console.log("Plugin not found");
process.exit(1);
}
};

await dynamic();
36 changes: 31 additions & 5 deletions src/streams/filter.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
import {Transform} from "stream";

const filter = () => {
// Write your code here
// Read from process.stdin
// Filter lines by --pattern CLI argument
// Use Transform Stream
// Write to process.stdout
const patternIndex = process.argv.indexOf("--pattern");
const pattern = patternIndex !== -1 ? process.argv[patternIndex + 1] : "";
let leftData = "";

const transformer = new Transform({
transform(chunk, _, callback) {
const data = leftData + chunk.toString();
const lines = data.split("\n");

leftData = lines.pop();

const filtered = lines
.filter((line) => line.includes(pattern))
.join("\n");

if (filtered) callback(null, filtered + "\n");
else callback();
},

flush(callback) {
if (leftData && leftData.includes(pattern)) {
callback(null, leftData + "\n");
} else {
callback();
}
},
});

process.stdin.pipe(transformer).pipe(process.stdout);
};

filter();
33 changes: 29 additions & 4 deletions src/streams/lineNumberer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
import {Transform} from "stream";

const lineNumberer = () => {
// Write your code here
// Read from process.stdin
// Use Transform Stream to prepend line numbers
// Write to process.stdout
let lineNumber = 1;
let leftData = "";

const transformer = new Transform({
transform(chunk, _, callback) {
const data = leftData + chunk.toString();
const lines = data.split("\n");

leftData = lines.pop();

const linesWithNumber = lines
.map((line) => `${lineNumber++} | ${line}`)
.join("\n");

callback(null, linesWithNumber + "\n");
},

flush(callback) {
if (leftData) {
callback(null, `${lineNumber} | ${leftData}\n`);
} else {
callback();
}
},
});

process.stdin.pipe(transformer).pipe(process.stdout);
};

lineNumberer();
53 changes: 47 additions & 6 deletions src/streams/split.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,49 @@
const split = async () => {
// Write your code here
// Read source.txt using Readable Stream
// Split into chunk_1.txt, chunk_2.txt, etc.
// Each chunk max N lines (--lines CLI argument, default: 10)
import fs from "fs";
import {Transform} from "stream";

const split = () => {
const linesIndex = process.argv.indexOf("--lines");
const linesNumber =
linesIndex !== -1 ? parseInt(process.argv[linesIndex + 1]) : 10;

const reader = fs.createReadStream("source.txt");

let leftData = "";
let lineCount = 0;
let fileIndex = 1;

let writer = fs.createWriteStream(`chunk_${fileIndex}.txt`);

const transformer = new Transform({
transform(chunk, _, callback) {
const data = leftData + chunk.toString();
const lines = data.split("\n");

leftData = lines.pop();

for (const line of lines) {
writer.write(line + "\n");
lineCount++;

if (lineCount >= linesNumber) {
writer.end();
fileIndex++;
writer = fs.createWriteStream(`chunk_${fileIndex}.txt`);
lineCount = 0;
}
}

callback();
},

flush(callback) {
if (leftData) writer.write(leftData + "\n");
writer.end();
callback();
},
});

reader.pipe(transformer);
};

await split();
split();
74 changes: 67 additions & 7 deletions src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,71 @@
import fs from "fs/promises";
import os from "os";
import {Worker} from "worker_threads";

const main = async () => {
// Write your code here
// Read data.json containing array of numbers
// Split into N chunks (N = CPU cores)
// Create N workers, send one chunk to each
// Collect sorted chunks
// Merge using k-way merge algorithm
// Log final sorted array
const sourceFile = await fs.readFile("./data.json", "utf-8");
const data = JSON.parse(sourceFile);

const cpuCores = os.cpus().length;

const chunkSize = Math.ceil(data.length / cpuCores);
const chunks = [];

for (let i = 0; i < cpuCores; i++) {
const start = i * chunkSize;
const end = start + chunkSize;
const chunk = data.slice(start, end);

if (chunk.length) {
chunks.push(chunk);
}
}
const sortedChunks = new Array(chunks.length);

const workers = chunks.map((chunk, index) => {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not obvious why we should update sortedChunks from worker function.
It's better to return the result inside worker function with resolve(sorted); so it will resolve with correct index automatically.

return new Promise((resolve, reject) => {
const worker = new Worker(new URL("./worker.js", import.meta.url));

worker.postMessage(chunk);

worker.on("message", (sorted) => {
sortedChunks[index] = sorted;
resolve();
});

worker.on("error", reject);
});
});
await Promise.all(workers);

const result = mergeSortedArrays(sortedChunks);
console.log(result);
};

const mergeSortedArrays = (arrays) => {
const result = [];
const indices = new Array(arrays.length).fill(0);

while (true) {
let minValue = Infinity;
let minIndex = -1;

for (let i = 0; i < arrays.length; i++) {
const index = indices[i];

if (index < arrays[i].length && arrays[i][index] < minValue) {
minValue = arrays[i][index];
minIndex = i;
}
}

if (minIndex === -1) break;

result.push(minValue);
indices[minIndex]++;
}

return result;
};

await main();
Loading