Skip to content

Instantly share code, notes, and snippets.

@asm-jaime
Last active May 12, 2018 05:04
Show Gist options
  • Save asm-jaime/3ebe0b5fb45c54e8be9c930e2ad037fe to your computer and use it in GitHub Desktop.
Save asm-jaime/3ebe0b5fb45c54e8be9c930e2ad037fe to your computer and use it in GitHub Desktop.
javascript braces validation, with use array and object as dictionary
// ========== array brace validation
const edict_arr = [
['[', ']'],
['(', ')'],
['{', '}'],
];
function valid_arr(braces){
const chars = braces.split('');
const stuck = [];
for(let i = 0; i < chars.length; ++i) {
for(let e = 0; e < edict_arr.length; ++e) {
if(chars[i] === edict_arr[e][0]){
stuck.push(chars[i]);
} else if(chars[i] === edict_arr[e][1]) {
const prev = stuck.pop();
if(edict_arr[e][0] !== prev){
return false;
}
}
}
}
if(stuck.length > 0) return false;
return true;
}
// ========== map bracke validation
const edict_map = {
'[':']',
'(':')',
'{':'}',
};
function revert_object(obj){
const res = Object.create(null);
for(e in obj) res[obj[e]] = e;
return res;
}
const edict_map_revert = revert_object(edict_map);
function valid_map(braces){
const chars = braces.split('');
const stuck = [];
for(let i = 0; i < chars.length; ++i) {
if(edict_map[chars[i]] !== undefined){
stuck.push(chars[i]);
} else {
// check proper symbols
if(edict_map_revert[chars[i]] === undefined) {
continue;
}
const prev = stuck.pop();
if(chars[i] !== edict_map[prev]){
return false;
}
}
}
if(stuck.length > 0) return false;
return true;
}
console.assert(valid_map("()")===true);
console.assert(valid_map("(){}[]")===true);
console.assert(valid_map("([{rrr}])")===true);
console.assert(valid_map("[(])")===false);
console.assert(valid_map("(}")===false);
console.assert(valid_map("[(])")===false);
console.assert(valid_map("[({eee})](]")===false);
console.assert(valid_arr("()")===true);
console.assert(valid_arr("(){}[]")===true);
console.assert(valid_arr("([{rrr}])")===true);
console.assert(valid_arr("[(])")===false);
console.assert(valid_arr("(}")===false);
console.assert(valid_arr("[(])")===false);
console.assert(valid_arr("[({eee})](]")===false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment