Skip to content

Instantly share code, notes, and snippets.

@erluxman
Created May 19, 2020 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erluxman/b14078511495bc822dfbc6895c273e15 to your computer and use it in GitHub Desktop.
Save erluxman/b14078511495bc822dfbc6895c273e15 to your computer and use it in GitHub Desktop.
Dart Range Extensions
void main() {
// 2,3,4,5,6,7,8,9,10
for (int i in 2.to(10)) {
print(i);
}
// 2,3,4,5,6,7,8,9
for (int i in 2.until(10)) {
print(i);
}
// 2,1,0,-1,-2,-3,-4,-5,-6,-7
for (int i in 2.to(-7)) {
print(i);
}
// 2,1,0,-1,-2,-3,-4,-5,-6
for (int i in 2.until(-7)) {
print(i);
}
}
extension Range on num {
List<num> until(num endPoint) {
var exclusive = to(endPoint);
exclusive.removeLast();
return exclusive;
}
List<num> to(num endPoint) {
var numbers = <num>[];
if (endPoint > this) {
for (int i = this; i <= endPoint; i++) {
numbers.add(i);
}
} else {
for (int i = this; i >= endPoint; i--) {
numbers.add(i);
}
}
return numbers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment