Skip to content

Instantly share code, notes, and snippets.

@s0nerik
Last active July 17, 2021 13:12
Show Gist options
  • Save s0nerik/104f0890a24739018432327a0eaf191d to your computer and use it in GitHub Desktop.
Save s0nerik/104f0890a24739018432327a0eaf191d to your computer and use it in GitHub Desktop.
Two way enum mapper
typedef EnumMapperCallback<T, E> = T Function(E value);
class EnumMapper<E, T> {
EnumMapper(List<E> enumValues, EnumMapperCallback<T, E> mapper) {
for (final enumValue in enumValues) {
final key = enumValue;
final value = mapper(enumValue);
_forwardMap[key] = value;
_inverseMap[value] = key;
}
}
final _forwardMap = <E, T>{};
final _inverseMap = <T, E>{};
T fromEnum(E value) => _forwardMap[value];
E toEnum(T value) => _inverseMap[value];
}
enum Messenger { viber, telegram, facebook }
final mapper = EnumMapper(
Messenger.values,
(type) {
switch (type) {
case Messenger.viber:
return 'viber';
case Messenger.telegram:
return 'telegram';
case Messenger.facebook:
return 'facebook';
}
},
);
void main() {
final telegramEnumValue = mapper.toEnum('TELEGRAM');
final telegramStringValue = mapper.fromEnum(Messenger.telegram);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment