题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
一直卡在includes和indexOf Error: Cannot read property 'includes' of undefined/Cannot read property 'indexOf' of undefined, 有了解情况的大神可以帮忙看一下为啥;
最后没办法 直接用正则表达式解决了,新学会了用变量建立正则表达式,同时在变量的基础之上加置首符号“^”, 这个也是之前一直无法解决的问题,好在今天阴差阳错解决了,完整代码如下:
while (line = readline()) {
console.log(commandMatch(line));
}
function commandMatch(str) {
let arr = [['reset', 'reset what'], ['reset board', 'board fault'],
['board add', 'where to add'], ['board delete', 'no board at all'],
['reboot backplane', 'impossible'], ['backplane abort', 'install first']];
let newArr = arr.map(x => [x[0].split(' '), x[1]]);
let command = str.split(' ');
let count = 0;
let res = [];
let output = '';
for (let i = 0; i < newArr.length; i++) {
if (command.length == 1) {
let regex1 = "^"+command[0]+"";
regex1 = new RegExp(regex1);
if (regex1.test(newArr[i][0][0]) && newArr[i][0].length == 1) {
count += 1;
res.push(newArr[i][1]);
}
}
if (command.length == 2) {
let regex2 = "^"+command[0]+"";
regex2 = new RegExp(regex2);
let regex3 = "^"+command[1]+"";
regex3 = new RegExp(regex3);
if (regex2.test(newArr[i][0][0]) && regex3.test(newArr[i][0][1])) {
count += 1;
res.push(newArr[i][1]);
}
}
}
if (count == 1) {
output = res[0];
}
else {
output = 'unknown command';
}
return output;
}
