Last active
December 20, 2015 00:39
-
-
Save ajlai/6043223 to your computer and use it in GitHub Desktop.
null-coalescing and input checking in 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
library coalesce; | |
// To turn the situation where we have: | |
// var foo; | |
// if (mightBeNullA != null) { | |
// foo = mightBeNullA; | |
// } else if (mightBeNullB != null) { | |
// foo = mightBeNullB; | |
// } else { | |
// foo = 2; | |
// } | |
// | |
// into: | |
// var foo = coalesce([mightBeNullA, mightBeNullB, 2]); | |
coalesce(Iterable values) => values.firstWhere((value) => value != null); | |
// For the simple case where we don't want an array every time we call it | |
coalesce2(value1, value2) => value1 == null ? value2 : value1; |
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
library presence; | |
// To turn the situation where we have: | |
// var arg = "rawvalue"; | |
// var accepted = ["foo", "bar", "baz"]; | |
// var default = "bar"; | |
// | |
// var foo; | |
// if(accepted.contains(arg)) { | |
// foo = arg; | |
// } else { | |
// foo = default; | |
// } | |
// | |
// into: | |
// var foo = presence(arg, accepted, orElse: default); | |
presence(value, Iterable values, {orElse: null}) => values.contains(value) ? value : orElse; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This'd be a good addition to taco_helpers. Here's a slightly different API that follows
List.firstWhere
's syntax.