Skip to content

Instantly share code, notes, and snippets.

@orllewin
Last active October 25, 2022 18:16
Show Gist options
  • Select an option

  • Save orllewin/73cba39958e07f4d7d319ecf90164e99 to your computer and use it in GitHub Desktop.

Select an option

Save orllewin/73cba39958e07f4d7d319ecf90164e99 to your computer and use it in GitHub Desktop.
reverberating-performance-7459

reverberating-performance-7459

Created with <3 with dartpad.dev.

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