I've done a test for a job (which I failed) and I'd like to know in which ways my code could've been better.
Here are the questions and my answers, it's not very long.
1) Make a program that checks if a string has balanced parentheses or brackets.
- Braces: (), [], <>
- For every closing brace, there must've been an opening, and for every open there must be a closure
- return 1 if it's balanced, or 0 if it isn't
My code:
const verify = (string) => {
// Array of the type of braces
var braces = ["(", ")", "[", "]", "<", ">"];
// Array half the length of braces Array
var balanced = Array.apply(null, {length: braces.length/2}).map(function() { return 0; });
for(let i = 0; i < string.length; ++i) {
let char = string[i], braceIndex = braces.indexOf(char);
if ( braceIndex == -1 ) {
// If current char is not any type of brace, continue.
continue;
}
// Get the index of the brace found halved and floored
let braceBalancingIndex = braceIndex / 2, braceFloor = Math.floor( braceBalancingIndex );
// If the halved index is equal to the index, then it must be an opening, else it must be a closing
if (braceBalancingIndex == braceFloor) {
balanced[braceFloor]++;
}
else {
balanced[braceFloor]--;
}
// If at any type being, the balance is negative, there was a closing without opening
for(let j = 0; j < balanced.length; ++j) {
if (balanced[j] < 0) return 0;
}
}
// If at the end the string is not balanced, there where more openings than closings
for(let i = 0; i < balanced.length; ++i) {
if (balanced[i] != 0) return 0;
}
return 1;
}