# 31. 模拟目录管理功能
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
class Node {
constructor(path, parent) {
this.path = path;
this.next = {};
if (parent) {
this.next['..'] = parent;
}
}
}
function isValidDirectoryName(name) {
return /^[a-z]+$/.test(name);
}
function isValidChangeDirectory(name) {
return name === '..' || isValidDirectoryName(name);
}
let root = new Node('/', null);
let currentNode = root;
let lastoutput = '';
rl.on('line', (line) => {
const parts = line.split(' ');
const command = parts[0];
if (command === 'mkdir' && parts.length === 2 && isValidDirectoryName(parts[1])) {
if (!currentNode.next[parts[1]]) {
currentNode.next[parts[1]] = new Node(currentNode.path+parts[1]+'/', currentNode)
}
} else if (command === 'cd' && parts.length === 2 && isValidChangeDirectory(parts[1])) {
const nextNode = currentNode.next[parts[1]];
if (nextNode) {
currentNode = nextNode;
}
} else if (command === 'pwd' && parts.length === 1) {
lastoutput = currentNode.path;
console.log(lastoutput);
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41