Skip to content

Instantly share code, notes, and snippets.

@ajlai
Last active December 20, 2015 00:39
Show Gist options
  • Save ajlai/6043223 to your computer and use it in GitHub Desktop.
Save ajlai/6043223 to your computer and use it in GitHub Desktop.
null-coalescing and input checking in dart
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;
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;
@danschultz
Copy link

This'd be a good addition to taco_helpers. Here's a slightly different API that follows List.firstWhere's syntax.

var value = coalesce([val1, val2], orElse: () => "val");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment