Last active
July 17, 2021 13:12
-
-
Save s0nerik/104f0890a24739018432327a0eaf191d to your computer and use it in GitHub Desktop.
Two way enum mapper
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
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]; | |
} |
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
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