Skip to content

Commit 47fe633

Browse files
committed
implementing ls and wc commands
1 parent 64e23bd commit 47fe633

2 files changed

Lines changed: 87 additions & 0 deletions

File tree

implement-shell-tools/ls/ls.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
const fs = require("fs");
2+
const path = require("path");
3+
const args = process.argv.slice(2);
4+
5+
let onePerLine = false;
6+
let showAll = false;
7+
let target = ".";
8+
9+
for (const arg of args) {
10+
11+
if (arg === "-1") {
12+
onePerLine = true;
13+
}
14+
else if (arg === "-a") {
15+
showAll = true;
16+
}
17+
else {
18+
target = arg;
19+
}
20+
}
21+
22+
const stats = fs.statSync(target);
23+
if (stats.isFile()) {
24+
console.log(path.basename(target));
25+
} else {
26+
27+
let files = fs.readdirSync(target);
28+
29+
if (!showAll) {
30+
files = files.filter(file => !file.startsWith("."));
31+
}
32+
if (onePerLine) {
33+
34+
for (const file of files) {
35+
console.log(file);
36+
}
37+
38+
} else {
39+
console.log(files.join(" "));
40+
}
41+
}

implement-shell-tools/wc/wc.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
const fs = require("fs");
2+
3+
const args = process.argv.slice(2);
4+
5+
let showWords = false;
6+
let showChars = false;
7+
let showLines = false;
8+
let fileNames = [];
9+
10+
// Check flags and file names
11+
for (let item of args) {
12+
if (item === "-l") {
13+
showLines = true;
14+
} else if (item === "-w") {
15+
showWords = true;
16+
} else if (item === "-c") {
17+
showChars = true;
18+
} else {
19+
fileNames.push(item);
20+
}
21+
}
22+
23+
// If no flags are given, show everything
24+
if (!showLines && !showWords && !showChars) {
25+
showLines = true;
26+
showWords = true;
27+
showChars = true;
28+
}
29+
30+
for (let fileName of fileNames) {
31+
let text = fs.readFileSync(fileName, "utf8");
32+
33+
let totalLines = text.split("\n").length - 1;
34+
let totalWords = text.trim().split(/\s+/).length;
35+
let totalChars = Buffer.byteLength(text);
36+
37+
let output = "";
38+
39+
if (showLines) output += totalLines + " ";
40+
if (showWords) output += totalWords + " ";
41+
if (showChars) output += totalChars + " ";
42+
43+
output += fileName;
44+
45+
console.log(output);
46+
}

0 commit comments

Comments
 (0)