-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathValidBraces.js
More file actions
31 lines (30 loc) · 1.34 KB
/
ValidBraces.js
File metadata and controls
31 lines (30 loc) · 1.34 KB
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
29
30
31
/**
* Write a function called validBraces that takes a string of braces,
* and determines if the order of the braces is valid.
* validBraces 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 four new characters.
* Open and closed brackets, and open and closed curly braces. Thanks to @arnedag for the idea!
*
* All input strings will be nonempty, and will only consist of
* open parentheses '(' , closed parentheses ')',
* open brackets '[', closed brackets ']',
* open curly braces '{' and closed curly braces '}'.
*
* What is considered Valid? A string of braces is considered valid if all braces are matched
* with the correct brace.
* For example:
* '(){}[]' and '([{}])' would be considered valid,
* while '(}', '[(])', and '[({})](]' would be considered invalid.
*
* Examples:
* validBraces( "(){}[]" ) => returns true
* validBraces( "(}" ) => returns false
* validBraces( "[(])" ) => returns false
* validBraces( "([{}])" ) => returns true
*/
const validBraces = (braces) => !removePatternRecursive(braces).length
const removePatternRecursive = (string, patterns = ['[]', '{}', '()']) =>
patterns.reduce((string, pattern) => string.split(pattern).length > 1
? removePatternRecursive(string.split(pattern).join(''))
: string, string)