Skip to content

Instantly share code, notes, and snippets.

@kranfix
Last active January 9, 2022 17:23
Show Gist options
  • Save kranfix/b237ce7310b9730c314d4980177916cf to your computer and use it in GitHub Desktop.
Save kranfix/b237ce7310b9730c314d4980177916cf to your computer and use it in GitHub Desktop.
Solution to var problem using extension methods in Dart
void main() {
final list = <int>[1, 2, 3, 4, 2, -1, 5];
final maxValue = 12;
final sum = list.clampedSum(maxValue);
/// ... more code that uses `sum` ...
}
extension ClampedAdder on List<int> {
int clampedSum(int maxValue) {
var sum = 0;
for(final val in this) {
sum += val;
}
if(sum > maxValue) {
sum = maxValue;
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment