Skip to content

Instantly share code, notes, and snippets.

@khadkarajesh
Created August 21, 2020 17:46
Show Gist options
  • Save khadkarajesh/bab7f294e2f64f9ce4ddb38cc193cd67 to your computer and use it in GitHub Desktop.
Save khadkarajesh/bab7f294e2f64f9ce4ddb38cc193cd67 to your computer and use it in GitHub Desktop.
Dart's collection extension methods
extension CollectionExtension<T> on List<T> {
bool isNullOrEmpty() {
return this == null || this.length == 0;
}
}
extension CollectionNumExtension<T extends num> on List<T> {
T max() {
if (this.isNullOrEmpty()) throw Exception("Provide collection with items");
this.sort();
return this[this.length - 1];
}
T min() {
if (this.isNullOrEmpty()) throw Exception("Provide collection with items");
this.sort();
return this[0];
}
double avg() {
if (this.isNullOrEmpty()) throw Exception("Provide collection with items");
return this.reduce((value, element) => value + element) / this.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment