Skip to content

Instantly share code, notes, and snippets.

@kwalrath
Forked from miquelbeltran/hint.txt
Last active December 18, 2019 18:38
Show Gist options
  • Save kwalrath/241c6bc591f9436a9be0116724222953 to your computer and use it in GitHub Desktop.
Save kwalrath/241c6bc591f9436a9be0116724222953 to your computer and use it in GitHub Desktop.
Use the methods `contains` and `startWith` from the `String` class.
// Implement the predicate of singleWhere
// with the following conditions
// * The element contains the character `'a'`
// * The element starts with the character `'M'`
String singleWhere(Iterable<String> items) {
return items.singleWhere(/* Implement predicate */);
}
String singleWhere(Iterable<String> items) {
return items.singleWhere((element) => element.startsWith('M') && element.contains('a'));
}
var items = [
'Salad',
'Popcorn',
'Milk',
'Toast',
'Sugar',
'Mozzarella',
'Tomato',
'Egg',
'Water',
];
void main() {
try {
final str = singleWhere(items);
if (str == 'Mozzarella') {
_result(true);
} else if (str == null) {
_result(false, [
'Tried calling singleWhere, but received a \'null\' value, the result '
'should be a non-null String'
]);
} else {
_result(false, [
'Tried calling singleWhere, but received $str instead of the expected '
'value \'Mozzarella\''
]);
}
} on StateError catch (stateError) {
_result(false, [
'Tried calling singleWhere, but received a StateError: ${stateError.message}. '
'singleWhere will fail if 0 or many elements match the '
'predicate'
]);
} catch (e) {
_result(false, [
'Tried calling singleWhere, but received an exception: $e'
]);
}
}
@miquelbeltran
Copy link

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