Skip to content

Instantly share code, notes, and snippets.

@miquelbeltran
Last active December 18, 2019 08:49
Show Gist options
  • Select an option

  • Save miquelbeltran/7ea77da468069db721b7363ef03f97c3 to your computer and use it in GitHub Desktop.

Select an option

Save miquelbeltran/7ea77da468069db721b7363ef03f97c3 to your computer and use it in GitHub Desktop.
filtering
Use the `where` method to implement the filters.
Iterable<User> filterUnder21(Iterable<User> users) {
// Implement this method
}
Iterable<User> findShortNamed(Iterable<User> users) {
// Implement this method
}
class User {
String name;
int age;
User(
this.name,
this.age,
);
}
Iterable<User> filterUnder21(Iterable<User> users) {
return users.where((user) => user.age >= 21);
}
Iterable<User> findShortNamed(Iterable<User> users) {
return users.where((user) => user.name.length <= 3);
}
var users = [
User('Alice', 21),
User('Bob', 17),
User('Claire', 52),
User('Dan', 12),
];
void main() {
try {
var out = filterUnder21(users);
if (out == null) {
_result(false, [
'Tried running `filterUnder21`, but received a null value. Did you implement the method?'
]);
return;
}
if (out.any((user) => user.age < 21) || out.length != 2) {
_result(false, ['Looks like `filterUnder21` is wrong, there are exactly two users with age under 21. Keep trying!']);
return;
}
} catch (e) {
_result(false, [
'Tried running `filterUnder21`, but received an exception: $e'
]);
return;
}
try {
var out = findShortNamed(users);
if (out == null) {
_result(false, [
'Tried running `findShortNamed`, but received a null value. Did you implement the method?'
]);
return;
}
if (out.any((user) => user.name.length > 3) || out.length != 2) {
_result(false, ['Looks like `findShortNamed` is wrong, there are exactly two users with a three letter name. Keep trying!']);
return;
}
} catch (e) {
_result(false, [
'Tried running `findShortNamed`, but received an exception: $e'
]);
return;
}
_result(true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment