简体   繁体   中英

How to use an enum to define another enum?

I have defined the following enum in JavaScript.:

/**
 * Represents the document type.
 * 
 * @enum
 */
var DOCUMENT_TYPE = {
    TC_INVOICE: 1,
    TC_CREDIT_NOTE: 2,
    OFFHIRE_INVOICE: 3,
    OFFHIRE_CREDIT_NOTE: 4
}

Now I want to define another enum for the document class "invoice" and "credit note". I tried something like this.:

/**
* Represents the document class ("invoice" or "credit note").
* 
* @enum
*/
var DOCUMENT_CLASS = {
    INVOICE: {
        1: DOCUMENT_TYPE.TC_INVOICE,
        3: DOCUMENT_TYPE.OFFHIRE_INVOICE
    },
    CREDIT_NOTE: {
        2: DOCUMENT_TYPE.TC_CREDIT_NOTE,
        4: DOCUMENT_TYPE.OFFHIRE_CREDIT_NOTE
    }
}

A database column holds the value for the document type (possible integer values: 1,2,3,4). Now I want check if it is an invoice or a credit note like:

if ( DOCUMENT_CLASS.INVOICE ) {
    doSomething();
} else if ( DOCUMENT_CLASS.CREDIT_NOTE ) {
    doSomeOtherThing();
}

This should do it:

if (DOCUMENT_CLASS.INVOICE[column]) {
    doSometjing();
} else if (DOCUMENT_CLASS.CREDIT_NOTE[column]) {
    doSomeOtherThing();
}

column is a variable holding the value from the database column you want to check.

Another way you could do this is by making the document classes arrays:

var DOCUMENT_CLASS = {
    INVOICE: [ DOCUMENT_TYPE.TC_INVOICE, DOCUMENT_TYPE.OFFHIRE_INVOICE ],
    CREDIT_NOTE: [ DOCUMENT_TYPE.TC_CREDIT_NOTE, DOCUMENT_TYPE.OFFHIRE_CREDIT_NOTE ]
};

Then you would write:

if (DOCUMENT_TYPE.INVOICE.indexOf(column) != -1) {
    doSomething();
} else if (DOCUMENT_TYPE.CREDIT_NOTE.indexOf(column) != -1) {
    doSomeOtherThing();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM