Created
February 24, 2022 20:21
-
-
Save stargazing-dino/24068ffdf2591ba506b40b220c7e80ae to your computer and use it in GitHub Desktop.
Retrieve the user ids of those whose ages are an even number
This file contains 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
import 'package:collection/collection.dart'; | |
// Given an array of User HashMaps with keys of Id and Age, | |
// write in Dart the code to return an array of User Ids for | |
// users whose Age is an even number. Make the code as efficient and terse as possible. | |
List<int> evenAgedUserIds(List<Map<String, dynamic>> usersEntries) { | |
return usersEntries | |
// ignore: avoid_dynamic_calls | |
.where((userEntry) => userEntry['age'] % 2 == 0) | |
.map((userEntry) => userEntry['id'] as int) | |
.toList(); | |
} | |
void main() { | |
// Comparing two lists in dart [1, 2] == [1, 2] with default equality doesn't | |
// actually work because it compares references. So instead, this does value | |
// comparison considering them a closed set. | |
Function listEquals = const ListEquality().equals; | |
final exampleUsers1 = <Map<String, dynamic>>[ | |
{"id": 1, "age": 21}, | |
{"id": 2, "age": 42}, | |
{"id": 3, "age": 20}, | |
]; | |
final exampleUsers2 = <Map<String, dynamic>>[ | |
{"id": -1, "age": 21}, | |
{"id": 0, "age": 2}, | |
{"id": double.infinity, "age": double.infinity}, | |
{"id": 17, "age": 0}, | |
// I didn't purposefully handle this case as requirements were for terseness. | |
// Although, in production I would definitely prefer complete type safety to | |
// avoid runtime errors: | |
// {"id": null , "age": null}, | |
]; | |
// I would actually use https://pub.dev/packages/test here to test but I don't think | |
// dartpad supports that package. | |
assert(listEquals(evenAgedUserIds(exampleUsers1), [2, 3])); | |
assert(listEquals(evenAgedUserIds(exampleUsers2), [0, 17])); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment