Skip to content
This repository was archived by the owner on Oct 22, 2024. It is now read-only.

int extension #228

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions lib/src/int_extensions.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/// Extensions that apply to all integers.
///
/// These extensions provide some generally useful convenience methods.
/// Credits to supercharged_dart
extension IntRange on int {
/// Creates an [Iterable<int>] that contains all values from current integer
/// until (including) the value [n].
///
/// Example:
/// ```dart
/// 0.rangeTo(5); // [0, 1, 2, 3, 4, 5]
/// 3.rangeTo(1); // [3, 2, 1]
/// ```
Iterable<int> rangeTo(int n) {
final count = (n - this).abs() + 1;
final direction = (n - this).sign;
var i = this - direction;
return Iterable.generate(count, (index) {
return i += direction;
});
}

/// Creates an [Iterable<int>] that contains all values from current integer
/// until (excluding) the value [n].
///
/// Example:
/// ```dart
/// 0.until(5); // [0, 1, 2, 3, 4]
/// 3.until(1); // [3, 2]
/// ```
Iterable<int> until(int n) {
if (this < n) {
return rangeTo(n - 1);
} else if (this > n) {
return rangeTo(n + 1);
} else {
return Iterable.empty();
}
}
}
25 changes: 25 additions & 0 deletions test/extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,34 @@
import 'dart:math' show pow, Random;

import 'package:collection/collection.dart';
import 'package:collection/src/int_extensions.dart';
import 'package:test/test.dart';

void main() {
group('int', () {
group('.until', () {
test('increase', () {
expect(1.until(5), iterable([1, 2, 3, 4]));
});
test('decrease', () {
expect(5.until(1), iterable([5, 4, 3, 2]));
});
test('same', () {
expect(1.until(1), Iterable.empty());
});
});
group('.rangeTo', () {
test('increase', () {
expect(1.rangeTo(5), iterable([1, 2, 3, 4, 5]));
});
test('decrease', () {
expect(5.rangeTo(1), iterable([5, 4, 3, 2, 1]));
});
test('same', () {
expect(1.rangeTo(1), iterable([1]));
});
});
});
group('Iterable', () {
group('of any', () {
group('.whereNot', () {
Expand Down