关于前端:node下实现多行输入-不用提前输入行数

实现计划:line事件中暂存输出行,利用debounce防抖,当暂定输出一段时间后将暂存的进行批量解决

以一道机试题为例
形容
明码要求:
1.长度超过8位
2.包含大小写字母.数字.其它符号,以上四种至多三种
3.不能有雷同长度大于2的子串反复
输出形容:
一组或多组长度超过2的字符串。每组占一行
输入形容:
如果符合要求输入:OK,否则输入NG

示例1
输出:
021Abc9000
021Abc9Abc1
021ABC9000
021$bc9000
复制
输入:
OK
NG
NG
OK

const readline = require('readline');

function isRepeatStr(str){
    let len = str.length - 2;
    for(let i = 0; i<len;i++){
        let subStr = str.substring(i,i+3);
        let tmpStr1 = str.substring(0,i);
        let tmpStr2 = str.substring(i+3);
        if(tmpStr1.indexOf(subStr) > 0)
            return true;
        if(tmpStr2.indexOf(subStr) > 0)
            return true;
    }
    return false;
}

function strWeight(str){
    let numWeight = 0;
    let upperWeight = 0;
    let lowerWeight = 0;
    let otherWeight = 0;
    str.split('').forEach(item=>{
        if(isNum(item)){
            numWeight = numWeight?numWeight:1;
        }
        else if(isUpperChar(item)){
            upperWeight = upperWeight?upperWeight:1;
        }
        else if(isLowerChar(item)){
            lowerWeight = lowerWeight?lowerWeight:1;
        }
        else
            otherWeight = otherWeight?otherWeight:1;
    })
    return numWeight+upperWeight+lowerWeight+otherWeight;
}

function isNum(str){
    return str.match(/[0-9]/) != null;
}

function isUpperChar(str){
    return str.match(/[A-Z]/) != null;
}

function isLowerChar(str){
    return str.match(/[a-z]/) != null;
}

function debounce(func, delay) {
    var timer;
    return function() {
      var context = this;
      clearTimeout(timer);
      timer = setTimeout(function() {
        func.apply(context, arguments);
        timer = undefined;
      }, delay || 20);
    };
};

function myProcess(str)
{   
    return (strWeight(str) >= 3) && (!isRepeatStr(str)) && (str.length > 8);
}

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let globalArray=[];
function processAll(){
    globalArray.forEach(line=>{
        if(myProcess(line) == true) {
            console.log('OK');
        } else {
            console.log('NG');
        }
    })
}
let delayProcess = debounce(processAll,20);
rl.on('line', function (line) {
    
    globalArray.push(line);
    
    delayProcess();
});

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理