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.

 Some programming languages as JAVA have reserved keywords to define enum structores. It is not the case of node.js. However, it is possible to define ENUM with Java Script / Node. using some strategies, as objects structures with constants.

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:

 https://github.com/rafaelqg/code/blob/main/enum_node.js


A video class about this theme is available here:



Comments

Popular posts from this blog

HASHLIB: Using HASH functions MD5 and SHA256

Spread Operator

Dart: implementing Object Oriented Programming (OOP)