Js Object Mapping

92 views Asked by At

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;
};
2

There are 2 answers

1
Matt On BEST ANSWER
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

3
Riad Baghbanli On

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.