Created
September 3, 2017 20:21
-
-
Save pokatomnik/e4178e908bfa96bd6fb4e223af8d05d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const braces = '(())'; | |
const checkConsistance = (str) => { | |
const res = str | |
.split('') | |
.reduce( | |
(acc, current) => ({ | |
'(': () => { ++acc['(']; return acc; }, | |
')': () => { ++acc[')']; return acc; } | |
})[current](), { | |
'(': 0, | |
')': 0 | |
} | |
); | |
return res['('] === res[')']; | |
} | |
const isValid = (str) => { | |
if (str[0] === ')') return false; | |
let res = str | |
.split('') | |
.reduce( | |
(acc, current) => ({ | |
'(': () => { if (acc.multiple) acc.appendedTwice = true; acc.stack.push('0'); return acc; }, | |
')': () => { if (acc.stack.length === 1) acc.multiple = true; acc.stack.pop(); return acc; } | |
})[current](), { | |
stack: [], | |
multiple: false, | |
appendedTwice: false | |
} | |
); | |
return (res.stack.length === 0) && !res.appendedTwice; | |
} | |
console.log(checkConsistance(braces)); | |
console.log(isValid(braces)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment