Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Валидация скобок (https://javascript.ru/forum/misc/85574-validaciya-skobok.html)

firep91613 26.10.2023 19:40

Валидация скобок
 
Подскажите, как улучшить/упростить?
function isValid(str) {
  const pairs = {
    '(': ')',
    '{': '}',
    '[': ']'
  }

  const stack = [];

  for (let s of str) {
    if (s == '(' || s == '{' || s == '[') {
      stack.push(pairs[s]);
    }

    if (s == ')' || s == '}' || s == ']') {
      if (s != stack[stack.length - 1]) {
        return false;
      } else {
        stack.pop(stack[stack.length - 1]);
      }
    }
  }

  return true;
}

console.log(isValid('(hello{world} and [me])'));  // true
console.log(isValid('(hello{world)} and [me])')); // false
console.log(isValid(')'));                        // false

Alexandroppolus 26.10.2023 20:04

function isValid(str) {
  const pairs = {
    '(': ')',
    '{': '}',
    '[': ']'
  };
  const closes = Object.values(pairs);

  const stack = [];

  for (let s of str) {
    if (pairs[s]) {
      stack.push(pairs[s]);
    } else if (closes.includes(s) && s !== stack.pop()) {
      return false;
    }
  }

  return !stack.length;
}

firep91613 27.10.2023 11:54

Alexandroppolus,
грамотно. Благодарю.


Часовой пояс GMT +3, время: 18:51.