Skip to content

Commit 309fe1c

Browse files
Refactor sorting logic in 'ls' command to improve code clarity and organization
1 parent 401e0ef commit 309fe1c

File tree

1 file changed

+21
-17
lines changed
  • implement-shell-tools/ls

1 file changed

+21
-17
lines changed

implement-shell-tools/ls/ls.js

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,16 @@ program
2525
program.parse(process.argv);
2626

2727

28+
29+
function sortEntries(entries) {
30+
// localeCompare = take into account rules of system language/region for ordering
31+
// undefined = uses the system default, numeric = regular number sorting, base = ignore case & accents
32+
return entries.sort((a, b) =>
33+
a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
34+
);
35+
}
36+
37+
2838
async function newLs(directory, oneFlag, allFlag) {
2939
try {
3040
// check if the path exists
@@ -37,28 +47,22 @@ async function newLs(directory, oneFlag, allFlag) {
3747
}
3848

3949
// read directory contents
40-
let entries = await fs.readdir(directory);
50+
const entries = await fs.readdir(directory);
4151

4252
let finalEntries;
53+
54+
// organize -a output (visible files (doesn't start with a .) and hidden files (starts with a .))
55+
const visibleFiles = entries.filter(name => !name.startsWith('.'));
56+
const hiddenFiles = entries.filter(name => name.startsWith('.') && name !== '.' && name !== '..');
4357

44-
// organize -a output ('.' and '..' first, then visible files, then hidden (starts with a .) files)
4558
if (allFlag) {
46-
const dotEntries = ['.', '..'];
47-
const visibleFiles = entries.filter(name => !name.startsWith('.'));
48-
const hiddenFiles = entries.filter(name => name.startsWith('.') && name !== '.' && name !== '..');
49-
50-
// localeCompare = take into account rules of system language/region for ordering
51-
// undefined = uses the system default, numeric = regular number sorting, base = ignore case & accents
52-
visibleFiles.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }));
53-
hiddenFiles.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }));
54-
55-
// combine to a single new array
56-
finalEntries = dotEntries.concat(visibleFiles, hiddenFiles);
59+
// add visible and hidden files to the new ['.', '..'] array literal
60+
finalEntries = ['.', '..']
61+
.concat(sortEntries(visibleFiles))
62+
.concat(sortEntries(hiddenFiles));
5763
} else {
58-
// sort just visible files
59-
finalEntries = entries
60-
.filter(name => !name.startsWith('.'))
61-
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }));
64+
// return sorted array with visible files
65+
finalEntries = sortEntries(visibleFiles);
6266
}
6367

6468
// organize -1 output

0 commit comments

Comments
 (0)