Skip to content

Instantly share code, notes, and snippets.

@iwillwen
Last active June 14, 2022 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwillwen/6dff507a0a4d7b3409277ef61d63437d to your computer and use it in GitHub Desktop.
Save iwillwen/6dff507a0a4d7b3409277ef61d63437d to your computer and use it in GitHub Desktop.
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);
}
}
@iwillwen
Copy link
Author

iwillwen commented Jun 14, 2022

class ConnectionShapeClass extends LabeledEnumType<string> {
  static Elbow = new ConnectionShapeClass('org.connection.elbow', 'Elbow')

  static RoundedElbow = new ConnectionShapeClass('org.connection.rounded-elbow', 'Rounded Elbow')

  static Fold = new ConnectionShapeClass('org.connection.fold', 'Fold')

  static RoundedFold = new ConnectionShapeClass('org.connection.rounded-fold', 'Rounded Fold')

  static Curve = new ConnectionShapeClass('org.connection.curve', 'Curve')
}

const shapeClassFromString = 'org.connection.curve'

const shapeClass = ConnectionShapeClass.fromValue(shapeClassFromString)
shapeClass.getLabel() //=> Curve

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment