0

What does the

var brackets = {
      '(': ')',
      '{': '}',
      '[': ']'
    };

From the following code do? Can you give examples of this kind of object in use? I know that objects can have methods and properties, but what does this mapping of brackets to opposite ones mean?

// Use an object to map sets of brackets to their opposites
var brackets = {
  '(': ')',
  '{': '}',
  '[': ']'
};

// On each input string, process it using the balance checker
module.exports = function (string) {
  var stack = [];
  // Process every character on input
  for (var i = 0; i < string.length; i++) {
    if (brackets[stack[stack.length - 1]] === string[i]) {
      stack.pop();
    } else {
      stack.push(string[i]);
    }
  }

  return !stack.length;
};
royhowie
  • 11,075
  • 14
  • 50
  • 67
badso
  • 109
  • 1
  • 11

2 Answers2

1

This code checks if all opening brackets have corresponding closing bracket in the given string. This is usual coding exercise from an interview. For some reason employers want to hire developers with good googling skills.

Riad Baghbanli
  • 3,105
  • 1
  • 12
  • 20
0
var brackets = {
  '(': ')',
  '{': '}',
  '[': ']'
};

The code above is the definition of a javaScript object named brackets. This object has three string fields that are set to values. The names of the fields happen to be '(', '{', '[', and the values happen to be ')', '}', ']' respectively.

They could have been:

var brackets = {
  'ABC': ')',
  'XYZ': '}',
  'BBC': ']'
};

I think you are just getting confused by the strange name for the variables. Which in this case are being used because this is parenthesis matching code.

To use these fields, you could used bracket notation:

var test = brackets['('];  

Which would give the string value of ')' to the test variable.

Dot notation:

brackets.(  

won't work because it is a special character. More info here: difference between dot notation and bracket notation in javascript

Community
  • 1
  • 1
Matt
  • 1,167
  • 1
  • 15
  • 26
  • 1
    The thing that is confusing me is how do I use this type of object property. For example, if I had an object var myObj = { property1 : "some property" } and I wanted to send a msg box to user it would be alert(myObj.property1);. For this brackets var, it would be alert(brackets['(']), and that's how it confuses me, because it's also an object but the way of representing its properties is different – badso Aug 18 '15 at 18:02