enum fooTypes {
"a" = "a",
"b" = "b",
"c" = "c",
"d" = "d"
}
interface IFooFlags {
[key: string]: boolean;
}
const defaultFooTypes = new Map<fooTypes, boolean>([
[fooTypes.a, true],
[fooTypes.b, true],
[fooTypes.c, true],
[fooTypes.d, true]
]);
const fooTypesMappings = new Map<fooTypes, boolean[]>([
[fooTypes.a, [true, false, false, false]],
[fooTypes.b, [false, true, false, false]],
[fooTypes.c, [false, false, true, false]],
[fooTypes.d, [false, false, false, true]]
]);
class MyClass {
private mappings = fooTypesMappings;
private fooTypes = defaultFooTypes;
private setFooTypes(values: boolean[]): void {
[...this.fooTypes.keys()].forEach((key, index) =>
this.fooTypes.set(key, values[index])
);
}
// In modern engines you can return:
// Object.fromEntries(this.fooTypes)
public getFooTypes(): IFooFlags {
return [...this.fooTypes].reduce(
(obj, { 0: key, 1: val }) => ({ ...obj, [key]: val }),
{}
);
}
public setFooTypeFlag(flag: fooTypes): void {
const flagTypes = this.mappings.get(flag);
if (!flagTypes) {
throw new Error("Invalid flag type");
}
this.setFooTypes(flagTypes);
}
}
const fooLover = new MyClass();
fooLover.setFooTypeFlag(fooTypes.d);
alert(JSON.stringify(fooLover.getFooTypes()));
Вот демонстрация этого