Languages
[Edit]
EN

TypeScript - iterate enum

13 points
Created by:
Marcin
16240

In TypeScript it is possible to itererate enum members in followin way.

interface IIteration {
    (name : string, value : string | number) : void;
}

class EnumUtils {
    private static EXPRESSION = /^[0-9]+$/g;

    public static iterate<T>(type : T, iteration : IIteration) {

        for(let name in type) {
            if(name.match(this.EXPRESSION))
                continue;
    
            iteration(name, <any>type[name]);
        }
    }
}

Example:

enum Fruit {
    Apple,
    Orange,
    Cherry
}

enum Car {
    BMW = 'BMW',
    Ford = 'FORD',
    Porshe = 'PORSHE'
}

enum Digit {
    One = 1,
    Two = 2,
    Three = 3
}

let iteration = (name : string, value : string | number) : void => {
    console.log(`${name} : ${value}`);
};

EnumUtils.iterate(Fruit, iteration);
EnumUtils.iterate(Car, iteration);
EnumUtils.iterate(Digit, iteration);

// or just:
// EnumUtils.iterate(Fruit, console.log);
// EnumUtils.iterate(Car, console.log);
// EnumUtils.iterate(Digit, console.log);

Output:

Apple : 0
Orange : 1
Cherry : 2

BMW : BMW
Ford : FORD
Porshe : PORSHE

One : 1
Two : 2
Three : 3

Run it online here.

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join