Created
November 16, 2022 08:39
-
-
Save plammens/234ac51c92a44aadcd906b4186f025d0 to your computer and use it in GitHub Desktop.
List slicing with step parameter in Dart
This file contains hidden or 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 ListSlice<T> on List<T> { | |
List<T> slice([int start = 0, int? end, int step = 1]) { | |
end ??= this.length; | |
return [for (var i = start; i < end; i += step) this[i]]; | |
} | |
} | |
void main() { | |
final list1 = [for (var i = 1; i <= 20; ++i) i]; | |
// Example - 1 | |
final result = list1.slice(1, 4); | |
print(result); // [2, 3, 4] | |
//Example - 2 | |
final result2 = list1.slice(10); | |
print(result2); // [11, 12, 13, 14, 15, 15, 17, 18, 19, 20] | |
//Example - 3 | |
final result4 = list1.slice(4, 10, 2); | |
print(result4); // [5, 7, 9] | |
//Example - 4 | |
final result3 = list1.slice(); | |
print(result3); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 17, 18, 19, 20] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment