How to write a function that recognises unbalanced brackets

前端 未结 2 1502
名媛妹妹
名媛妹妹 2021-01-17 05:46

I am trying to write a function that checks if a syntax is correct or not. If it is correct it returns \'ok\' else it returns the index of the error. So far my code works if

2条回答
  •  生来不讨喜
    2021-01-17 06:34

    You could take a an array for the index of each opening character and pop this if the related closing character is found.

    If finished and the stack has no item, the syntax is ok, otherwise return an index or the index of the last pushed opening character.

    Example:

    code        comment
    ----------- ---------------------------
    [][[[]][][]
    []          balanced
      [         error, this returns later 2
       [[]]     balanced
           []   balanced
             [] balanced
                finally a missing ]
    

    function syntaxError(syntax) {
        const
            isOpening = c => /[<[{(]/.test(c),
            isClosing = c => /[>\]})]/.test(c),
            open = { '>': '<', ']': '[', '}': '{', ')': '(' };
    
        var stack = [],
            index,
            finished = Array
                .from(syntax)
                .every((c, i) => {
                    var temp = stack[stack.length - 1];
                    if (isOpening(c)) {
                        if (temp && temp.c === c) {
                            temp.indices.push(i);
                        } else {
                            stack.push({ c, indices: [i] });
                        }
                        return true;
                    }
                    if (isClosing(c)) {
                        if (temp && temp.c === open[c]) {
                            temp.indices.pop();
                            if (!temp.indices.length) stack.pop();
                        } else {
                           index = stack.length ? stack.pop().indices.pop() : i;
                           return false;
                        }
                    }
                    return true;
                });
    
        return finished && !stack.length
            ? 'ok'
            : index === undefined
                ? stack.pop().indices.pop()
                : index;
    }
    
    console.log(syntaxError('[][][[{}]]'));  // ok
    
    console.log(syntaxError(')'));
    //                       0
    
    console.log(syntaxError('[][][[{<}]]'));
    //                       01234567
    
    console.log(syntaxError('[][[[]][][]'));
    //                       012
    
    console.log(syntaxError('[[[[[[[[[[[[[[]]]]]]]]<<<<<<<<<<<>>>>>>>>>>>]]]]]]'+'[[[[[[[[[[[[[[]]]]]]]<<<<<<<<<<<>>>>>>>>>>>]}]]]]' + '>'));

提交回复
热议问题