Skip to content
34 changes: 34 additions & 0 deletions implement-shell-tools/cat/cat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const fs = require("fs");

const args = process.argv.slice(2);

const showLineNumbers = args.includes("-n");
const numberNonEmptyLines = args.includes("-b");

const files = args.filter(arg => arg !== "-n" && arg !== "-b");

for (const file of files) {
const content = fs.readFileSync(file, "utf8");

if (numberNonEmptyLines) {
const lines = content.split("\n");
let lineNumber = 1;

lines.forEach((line) => {
if (line.trim() !== "") {
console.log(`${lineNumber} ${line}`);
lineNumber++;
} else {
console.log(line);
}
});
} else if (showLineNumbers) {
const lines = content.split("\n");

lines.forEach((line, index) => {
console.log(`${index + 1} ${line}`);
});
} else {
process.stdout.write(content);
}
}
21 changes: 21 additions & 0 deletions implement-shell-tools/ls/ls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const fs = require("fs");

const args = process.argv.slice(2);

const showAll = args.includes("-a");

// remove -a from arguments
const filteredArgs = args.filter(arg => arg !== "-a");

const target = filteredArgs[0] || ".";

let files = fs.readdirSync(target);

// hide hidden files if -a is NOT used
if (!showAll) {
files = files.filter(file => !file.startsWith("."));
}

files.forEach(file => {
console.log(file);
});
29 changes: 29 additions & 0 deletions implement-shell-tools/wc/wc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const fs = require("fs");

const args = process.argv.slice(2);

const showLines = args.includes("-l");
const showWords = args.includes("-w");
const showChars = args.includes("-c");

const files = args.filter(
(arg) => arg !== "-l" && arg !== "-w" && arg !== "-c"
);

for (const file of files) {
const content = fs.readFileSync(file, "utf8");

const lines = content.split("\n").length;
const words = content.trim().split(/\s+/).length;
const chars = content.length;

if (showLines) {
console.log(lines, file);
} else if (showWords) {
console.log(words, file);
} else if (showChars) {
console.log(chars, file);
} else {
console.log(lines, words, chars, file);
}
}