Enumerations
JavaScript getter syntax offers an alternative to using switch to dispatch or route functions with zero parameters:
const TrafficLight = {
get red() {
return "red";
},
get yellow() {
return "yellow";
},
"green: "green"
};
Then TrafficLight["red"] returns "red". In this simple example, it’s just a more convoluted way of getting a string keyword to return itself, which can be turn in a more conventional ways as in the “green” example, but illustrates an ellegant way to use methods in object literals.
A workaround for no paramter passing to getters is to have them share scope with the required data. They can also mutate an object they share scope with.
describe("Module Scope", function() {
const myObj = {};
const myEnum = {
get red() {
myObj.color = "red";
},
get yellow() {
myObj.color = "yellow";
},
get green() {
myObj.color = "green";
}
};
it ('myEnum["red"] should mutate myObj.color to "red"', function() {
myEnum["red"];
expect(myObj.color).toBe("red");
});
});