ENUM with NodeJS
ENUMS are a type of structure which assists in the source code legibility. Instead of defining hard-code values in the source code, like “0”, null, or generic types such 0 or 1 or 2, it is possible to define friendly names with the meaning of such values, normally even related to some business vocabulary, for instance: 0=> GREEN, 1=> BLUE and 2:> RED.
Here you
can see one example of enum definition
const RECTANGLE_DIMENSIONS
= {
SMALL:[10,20],
MEDIUM:[20,
40],
LARGE:
[40, 80],
};
Once it is defined, we can make refence to its values using the constant names, improving de readability of the source code. Observe in the example below the enum values being used as parameter in the objects constructor.
class Rectangle{
width=0;
height=0;
constructor(dimensions){
this.width=dimensions[0];
this.height=dimensions[1];
}
area(){
return
this.width*this.height;
}
}
let r1=
new Rectangle(RECTANGLE_DIMENSIONS.SMALL);
let r2=
new Rectangle(RECTANGLE_DIMENSIONS.MEDIUM);
let r3=
new Rectangle(RECTANGLE_DIMENSIONS.LARGE);
console.log(r1,r1.area());
console.log(r2,r2.area());
console.log(r3,r3.area());
You can
download this source code from:
A video
class about this theme is available here:
Comments
Post a Comment