-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path51-valid-braces.js
28 lines (26 loc) · 1.01 KB
/
51-valid-braces.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Write a function that takes a string of braces, and determines if the order of
// the braces is valid.It should return true if the string is valid, and false if it's invalid.
// This Kata is similar to the Valid Parentheses Kata, but introduces new characters:
// brackets [], and curly braces {}. Thanks to @arnedag for the idea!
//
// All input strings will be nonempty, and will only consist of
// parentheses, brackets and curly braces: ()[]{}.
//
// What is considered Valid?
//
// A string of braces is considered valid if all braces are matched with the correct brace.
//
// Examples
//
// "(){}[]" => True
// "([{}])" => True
// "(}" => False
// "[(])" => False
// "[({})](]" => False
const validBraces = ([brace, ...rest], stack = []) => {
const obj = { '(': ')', '[': ']', '{': '}' };
if (!brace && !stack.length) { return true; }
if (obj[brace]) { return validBraces(rest, [brace, ...stack]); }
if (brace === obj[stack[0]]) { return validBraces(rest, stack.slice(1)); }
return false;
};