DEV Community

Discussion on: code every day with me

Collapse
lukeshiru profile image
LUKESHIRU

A few tips:

  • Avoid single letter names such as s or x, your teammates and your future self will be thankful.
  • Try to always use === and !== instead of == and != which are less reliable.
  • You can use a plain object instead of a map:
const map = {
    "[": "]",
    "(": ")",
    "{": "}"
};
Enter fullscreen mode Exit fullscreen mode
  • When working with boolean expresions, you don't need a ternary, so you can change this:
return stack.length == 0 && closeChar.length == 0 ? true : false;
Enter fullscreen mode Exit fullscreen mode

With this:

return stack.length === 0 && closeChar.length === 0;
Enter fullscreen mode Exit fullscreen mode

Finally, here is my version using your same logic but without any for, return or anything like that:

const isValid = string =>
    string.length % 2 === 0 &&
    [...string]
        .reduce(
            ([stack, closeChar], char) =>
                "([{".includes(char)
                    ? [[...stack, char], closeChar]
                    : char ===
                      {
                            "[": "]",
                            "(": ")",
                            "{": "}"
                      }[stack[stack.length - 1]]
                    ? [stack.slice(0, -1), closeChar]
                    : [stack, [...closeChar, char]],
            [[], []]
        )
        .every(array => array.length === 0);
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
coderduck profile image
duccanhole Author

many thanks