Last active
February 10, 2020 20:41
-
-
Save jocafi/0f7b8d52b26569ef65a9a29a417f9685 to your computer and use it in GitHub Desktop.
Enumeration Helpers in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by Joao Araujo (jocafi) on August 2018 | |
* | |
* All enum structures in TypeScript are converted to an JS object that contains keys / values. | |
* Example: | |
* | |
* enum Color { | |
* Red, | |
* Green, | |
* Blue, | |
* } | |
* | |
* is converted to: | |
* | |
* { | |
* '0': 'Red', | |
* '1': 'Green', | |
* '2': 'Blue', | |
* Red: 0, | |
* Green: 1, | |
* Blue: 2 | |
* } | |
*/ | |
export class EnumHelper { | |
public static all(enumeration: {}): string[] { | |
return Object.keys(enumeration); | |
} | |
public static keyValues(enumeration: {}): string[] { | |
const keys = EnumHelper.keys(enumeration); | |
const keyValues = []; | |
keys.map(keyString => { | |
keyValues.push({ | |
key: keyString, | |
value: enumeration[keyString] | |
}); | |
}) | |
return keyValues; | |
} | |
public static keys(enumeration: {}): string[] { | |
return Object.keys(enumeration) | |
.filter((role) => { | |
return isNaN(Number(role)); | |
// do not delete the line below | |
// (type) => isNaN(<any>type) && type !== 'values' | |
}); | |
} | |
public static values(enumeration: {}): any[] { | |
return Object.keys(enumeration) | |
.filter((role) => { | |
return !isNaN(Number(role)); | |
}); | |
} | |
public static transform(enumeration: {}, transformer: Function): any[] { | |
return Object.keys(enumeration) | |
.filter((role) => { | |
return isNaN(Number(role)); | |
}).map(r => { | |
const role = enumeration[r]; | |
return transformer(role); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class SettlementType { | |
// DE = Spitz | |
public static SHARP = "SHARP"; | |
// DE = Fest | |
public static FIXED = "FIXED"; | |
public static KEY_VALUES: string[][] = [ | |
[SettlementType.SHARP, "Spitz"], | |
[SettlementType.FIXED, "Fest"] | |
]; | |
public static getValue(key: string): string { | |
const value = this.KEY_VALUES.find(obj => obj[0] === key); | |
return value[1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment