Skip to content

Instantly share code, notes, and snippets.

@pokatomnik
Created September 3, 2017 20:21
Show Gist options
  • Save pokatomnik/e4178e908bfa96bd6fb4e223af8d05d4 to your computer and use it in GitHub Desktop.
Save pokatomnik/e4178e908bfa96bd6fb4e223af8d05d4 to your computer and use it in GitHub Desktop.
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