Created with <3 with dartpad.dev.
Last active
October 25, 2022 18:16
-
-
Save orllewin/73cba39958e07f4d7d319ecf90164e99 to your computer and use it in GitHub Desktop.
reverberating-performance-7459
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() { | |
| print('DartWhen'); | |
| var x = 1; | |
| when(x, { | |
| 1: () => print("is 1"), | |
| 2: () => print("is 2"), | |
| 3: () { | |
| print("is 3"); | |
| print("Code block"); | |
| }, | |
| x > 500: () => print("> 500"), | |
| Default: () => print("default - no match") | |
| }); | |
| var y = when(x, {1: 11, 2: 22, 3: 33, x > 500: 0, Default: -1}); | |
| print("y: $y"); | |
| } | |
| class Default {} | |
| dynamic when<T>(T condition, Map<dynamic, dynamic> branches) { | |
| var consumed = false; | |
| dynamic returnValue; | |
| branches.forEach((key, value) { | |
| if (key.runtimeType == condition.runtimeType && key == condition) { | |
| if (value is Function) { | |
| value.call(); | |
| consumed = true; | |
| } else { | |
| returnValue = value; | |
| consumed = true; | |
| } | |
| } else if (key.runtimeType == bool && key as bool == true) { | |
| if (value is Function) { | |
| value.call(); | |
| consumed = true; | |
| } else { | |
| returnValue = value; | |
| consumed = true; | |
| } | |
| } | |
| }); | |
| if (consumed) { | |
| return returnValue; | |
| } else { | |
| if (branches.containsKey(Default)) { | |
| branches[Default].call(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment