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;
};
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:
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:
Which would give the string value of ')' to the test variable.
Dot notation:
won't work because it is a special character. More info here: difference between dot notation and bracket notation in javascript