inclusive function
Generates an inclusive List of integers. inclusive(3) returns (0, 1, 2, 3). inclusive(-3) returns (-3, -2, -1, 0).
inclusive(1, 3) returns (1, 2, 3). inclusive(-3, -1) returns (-3, -2, -1). inclusive(0, -3) returns (0, -1, -2, -3).
Optional step must be positive if a < b, negative if a > b.
inclusive(1, 3, 2) returns (1, 3).
inclusive(-3, 1, 2) returns (-3, -1, 1).
inclusive(1, -3, -2) returns (1, -1, -3).
Implementation
Iterable<int> inclusive(int a, [int? b, int? step]) sync* {
// Only one argument given
if (b == null) {
if (a >= 0) {
for (int i = 0; i <= a; i++) {
yield i;
}
} else {
for (int i = a; i <= 0; i++) {
yield i;
}
}
return;
}
if (a < b) {
if (step != null && step <= 0) {
throw ArgumentError('step must be positive if beginning < end');
}
for (int i = a; i <= b; i += step ?? 1) {
yield i;
}
} else if (a > b) {
if (step != null && step >= 0) {
throw ArgumentError('step must be negative if beginning > end');
}
for (int i = a; i >= b; i += step ?? -1) {
yield i;
}
} else {
yield a;
}
}