createInterface has a member called completer
which is exactly made for autocompletion, yet the tests are written in such a way that using the completer function is not accapted as it’s matches aren’t separated by 2 spaces and I haven’t found a way to change that.
So if you use the built-in way that is also recommended in the code that is given to you, you can’t complete this challange, or at least I haven’t found a way. Here is my relevant code:
const rl = createInterface({
input: process.stdin,
output: process.stdout,
prompt: "$ ",
completer: handleCompletion,
});
let previousLine = "";
function handleCompletion(line: string) {
const matches = Array.from(Commands.keys())
.filter((command) => command.startsWith(line))
.map((input) => `${input} `);
const executables: string[] = [];
for (const dir of (process.env.PATH || "").split(PATH_SEPARATOR)) {
try {
const files = fs.readdirSync(dir);
executables.push(
...files
.filter((file) => file.startsWith(line))
.map((input) => `${input} `)
);
} catch (err) {
// Ignore errors (e.g., if a path does not exist)
}
}
if (!matches.length && !executables.length) {
process.stdout.write("\u0007"); // Ring bell if no matches
return [[], line];
}
if (line !== previousLine && [...matches, ...executables].length > 1) {
process.stdout.write("\u0007"); // Ring bell on first match
previousLine = line;
return [[], line];
}
return [[...matches, ...executables], line];
}
Results: