Created
May 19, 2020 02:33
-
-
Save erluxman/b14078511495bc822dfbc6895c273e15 to your computer and use it in GitHub Desktop.
Dart Range Extensions
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
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