Created
December 11, 2021 19:02
-
-
Save 3AHAT0P/8733ccf2a443b4eff2536fe2fcddd6dd to your computer and use it in GitHub Desktop.
Selector pattern on the dart
This file contains hidden or 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
void main() { | |
final selector = Selector(); | |
selector | |
.when((value) => value == 3).then((value) => value * 2) | |
.whenIsEqual((value) => value == 'QQQ').then((value) { print(value); return null; }) | |
.fallback((value) => { 'x': 42 }); | |
final selector2 = Selector<int, int>(); | |
selector2 | |
.when((value) => value == 3).then((value) => value * 2) | |
.whenIsEqual('QQQ').then((value) { print(value); return null; }) | |
.fallback((value) => { 'x': 42 }); | |
print(selector(15)); | |
print(selector('QQQ')); | |
print(selector('asd')); | |
print(selector(3)); | |
} | |
class Selector<TArgument, TReturn> { | |
final Map<bool Function(TArgument value), TReturn Function(TArgument value)> _cases = {}; | |
TReturn Function(TArgument value)? _fallback; | |
bool Function(TArgument value)? _currentCondition; | |
Selector(); | |
TReturn call(TArgument value) { | |
for (final someCase in _cases.entries) { | |
if (someCase.key(value)) return someCase.value(value); | |
} | |
if (_fallback != null) return _fallback!(value); | |
throw Exception('fallback function is not defined'); | |
} | |
Selector<TArgument, TReturn> when(bool Function(TArgument value) conditionFn) { | |
_currentCondition = conditionFn; | |
return this; | |
} | |
Selector<TArgument, TReturn> whenIsEqual(TArgument checkedValue) { | |
_currentCondition = (value) => value == checkedValue; | |
return this; | |
} | |
Selector<TArgument, TReturn> then(TReturn Function(TArgument value) runnerFn) { | |
if (_currentCondition == null) throw Exception('You couldn\'t use "then" without "when*"'); | |
_cases[_currentCondition!] = runnerFn; | |
return this; | |
} | |
Selector<TArgument, TReturn> fallback(TReturn Function(TArgument value) runnerFn) { | |
_fallback = runnerFn; | |
return this; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment