michaelp0730
2/10/2015 - 9:44 PM

BracesValidator.js

function validBraces(braces){
  var openersToClosers = {
    '(' : ')',
    '[' : ']',
    '{' : '}'
  };
  
  var openers = Object.keys(openersToClosers);
  var openersStack = [];
  var closers = [];
  var lastUnclosedOpener;
  
  for (var o in openersToClosers) {
    closers.push(openersToClosers[o]);
  }
  
  for (var i = 0; i < braces.length; i++) {
    if (openers.indexOf(braces[i]) !== -1) {
      openersStack.push(braces[i]);
    } else if (closers.indexOf(braces[i]) !== -1) {   
      if (openersStack.length === 0) {
        return false;
      } else {
        lastUnclosedOpener = openersStack.pop();
        if (openersToClosers[lastUnclosedOpener] !== braces[i]) {
          return false;
        }
      }
    }
  }
    
  return openersStack.length === 0;
}