题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// 预定义一个命令对象
const commandObj = {
'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',
}
// 上面对象的键值的组成的数组
const commandKeys = Object.keys(commandObj)
// 上面的数组转成二维数组 [['reset'], ['reset','board']....]
const arr = commandKeys.map(item=>item.split(' '))
rl.on('line', function (line) {
// 筛选出匹配的命令,再使用命令作为key去commandObj对象获取值打印
const keys = line.split(' ')
// 只有一个词,则只能匹配第一个命令,其他命令就算匹配上也是不成功的
if(keys.length === 1){
if(commandKeys[0].includes(keys[0])){
console.log('reset what')
}else {
console.log('unknown command')
}
}else if(keys.length === 2){
// 循环遍历输入的关键字,一个一个判断是否匹配上
console.log(handleMatch(keys, arr))
}
});
/**
* 匹配上且命令唯一则返回对应的命令
* 否则返回 unknown command
*/
function handleMatch(keys: string[], arr: any[]){
let res = []
for(let j = 1; j < arr.length; j++ ){
// 当两个关键词分别匹配上命令的第一和第二个字符串时,就添加到res
// 注意需要从第一个开始匹配,不能只是包含就可以了,所以应该需要使用正则
const reg1 = new RegExp(`^${keys[0]}`,"g");
const reg2 = new RegExp(`^${keys[1]}`,"g");
if(reg1.test(arr[j][0]) && reg2.test(arr[j][1]) ){
res.push(arr[j].join(' '))
}
}
// 唯一则返回命令
if(res.length === 1){
return commandObj[res[0]]
}else {
// 不唯一或者没有
return 'unknown command'
}
}
查看22道真题和解析