Created
August 21, 2020 15:51
-
-
Save khadkarajesh/7bc9be0330fae8bb771a5636b6c04592 to your computer and use it in GitHub Desktop.
dart's collection extension
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
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; | |
} | |
} | |
extension CollectionStringExtension<T extends String> on List<T> { | |
String joinToString(String separator, | |
{String prefix = "", String postfix = ""}) { | |
return prefix + this.join(separator) + postfix; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment