Last active
June 14, 2022 09:38
-
-
Save iwillwen/6dff507a0a4d7b3409277ef61d63437d to your computer and use it in GitHub Desktop.
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 LabeledEnumType<T = number> { | |
private value: T; | |
private label: string; | |
private props: Map<string, unknown> = new Map<string, unknown>(); | |
constructor(value: T, label: string, props: Record<string, unknown> = {}) { | |
this.value = value; | |
this.label = label; | |
for (const key of Object.keys(props)) { | |
this.props.set(key, props[key]); | |
} | |
} | |
static enumValues<T>() { | |
const values: LabeledEnumType<T>[] = Object.values(this).filter( | |
(prop) => prop instanceof this | |
); | |
return values; | |
} | |
static fromValue<T>(value: T) { | |
return this.enumValues().find((obj) => obj.value === value); | |
} | |
static fromLabel<T>(label: string) { | |
return this.enumValues<T>().find((obj) => obj.label === label); | |
} | |
static fromProp(key: string, value: unknown) { | |
return this.enumValues().find((obj) => obj.getProp(key) === value); | |
} | |
getValue() { | |
return this.value; | |
} | |
getLabel() { | |
return this.label; | |
} | |
getProp(key: string) { | |
return this.props.get(key); | |
} | |
setProp(key: string, value: unknown) { | |
return this.props.set(key, value); | |
} | |
} |
Author
iwillwen
commented
Jun 14, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment