DEV Community

Aliafify
Aliafify

Posted on

JavaScript brackets Challenge

write JavaScript function which take an a string of brackets as argument and return true if brackets with valid order ' { ( ) [ ] }' and false if brackets in invalid order [ ( ] ){ }

const bracketsString = '(){}[]'
function distribution(a){
 const b = a.split(''); // array of brackets 
const types =[{type:'{',name:'cur',close:'}'},{type:'(',name:'br',close:')'},{type:'[',name:'sq',close:']'}]

let valid =true;
    for (i = 0; i < b.length; i++) {
        if (!valid) { break }
        const Type = types.filter(t => t.type === b[i]);
        if (Type.length === 0) { continue; }
        const close = Type[0].close;

        let closeIndexs = [];
        for (i = i + 1; i < b.length; i++) {

            if (b[i] === close) {
                closeIndexs.push(i);

            }

        }
        if (closeIndexs.length === 0) {
            valid = false
            break;
        }
        const closeIndex = closeIndexs[0] 
        if (i % 2 === 0 && closeIndex % 2 !== 0) {
            return valid = true;
        }
        else if (i + 1 % 2 === 0 && closeIndex + 1 % 2 !== 0) {
            valid = true;
        }
        else { valid = false }

    }
return valid;
}
console.log( distribution(bracketsString))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)