Skip to content

Range abstract

abstract class Range with RIterableOnce<int>, RIterable<int>, RSeq<int>, IndexedSeq<int>

An immutable, O(1)-memory integer range.

Elements are computed on demand from start, end, and step. All IndexedSeq operations are available. Most operations return another Range; those that cannot (e.g. map) fall back to a general sequence.

Construct with Range.exclusive (half-open [start, end)) or Range.inclusive (closed [start, end]).

dart
Range.exclusive(0, 5).toIList();           // IList(0, 1, 2, 3, 4)
Range.inclusive(1, 5, 2).toIList();        // IList(1, 3, 5)
Range.exclusive(5, 0, -1).toIList();       // IList(5, 4, 3, 2, 1)

Available Extensions

Constructors

Range()

Range(int start, int end, int step)
Implementation
dart
Range(this.start, this.end, this.step);

Range.exclusive() factory

factory Range.exclusive(int start, int end, [int step = 1])

Creates a half-open range [start, end) with the given step.

Implementation
dart
factory Range.exclusive(int start, int end, [int step = 1]) => _RangeExclusive(start, end, step);

Range.inclusive() factory

factory Range.inclusive(int start, int end, [int step = 1])

Creates a closed range [start, end] with the given step.

Implementation
dart
factory Range.inclusive(int start, int end, [int step = 1]) => _RangeInclusive(start, end, step);

Properties

end final

final int end

The bound of the range (exclusive or inclusive, see isInclusive).

Implementation
dart
final int end;

hashCode no setter override

int get hashCode

The hash code for this object.

A hash code is a single integer which represents the state of the object that affects operator == comparisons.

All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).

If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.

Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.

Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.

If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.

Implementation
dart
@override
int get hashCode =>
    length > 2 ? MurmurHash3.rangeHash(start, step, _lastElement) : super.hashCode;

head no setter override

int get head

Returns the first element of this collection, or throws if it is empty.

Implementation
dart
@override
int get head => isEmpty ? throw _emptyRangeError('head') : start;

headOption no setter inherited

Option<int> get headOption

Returns the first element of this collection as a Some if non-empty. If this collction is empty, None is returned.

Inherited from RIterable.

Implementation
dart
Option<A> get headOption {
  final it = iterator;
  return Option.when(() => it.hasNext, () => it.next());
}

init no setter override

Range get init

Returns all elements from this collection except the last. If this collection is empty, an empty collection is returned.

Implementation
dart
@override
Range get init => isEmpty ? throw _emptyRangeError('init') : dropRight(1);

inits no setter override

RIterator<Range> get inits

Returns an iterator of all potential tails of this collection, starting with the entire collection and ending with an empty one.

Implementation
dart
@override
RIterator<Range> get inits => _RangeInitsIterator(this);

isEmpty no setter override

bool get isEmpty

Whether this collection contains no elements.

Implementation
dart
@override
bool get isEmpty =>
    (start > end && step > 0) || (start < end && step < 0) || (start == end && !isInclusive);

isInclusive no setter

bool get isInclusive

Whether end is included in the range.

Implementation
dart
bool get isInclusive;

isNotEmpty no setter inherited

bool get isNotEmpty

Whether this collection contains at least one element.

Inherited from RIterableOnce.

Implementation
dart
bool get isNotEmpty => !isEmpty;

isTraversableAgain no setter inherited

bool get isTraversableAgain

Whether this collection can be traversed more than once.

Always false for a bare RIterableOnce; overridden to true by RIterable and its subtypes.

Inherited from RIterableOnce.

Implementation
dart
bool get isTraversableAgain => false;

iterator no setter override

RIterator<int> get iterator

Returns an RIterator over the elements of this collection.

Implementation
dart
@override
RIterator<int> get iterator => _RangeIterator(start, step, _lastElement, isEmpty);

knownSize no setter inherited

int get knownSize

Returns the number of elements in this collection, if that number is already known. If not, -1 is returned.

Inherited from RIterableOnce.

Implementation
dart
int get knownSize => -1;

last no setter override

int get last

Returns the last element of this collection, or throws if it is empty.

Implementation
dart
@override
int get last => isEmpty ? throw _emptyRangeError('last') : _lastElement;

lastOption no setter inherited

Option<int> get lastOption

Returns the last element of this collection as a Some, or None if this collection is empty.

Inherited from RIterable.

Implementation
dart
Option<A> get lastOption {
  if (isEmpty) {
    return none();
  } else {
    final it = iterator;
    var last = it.next();

    while (it.hasNext) {
      last = it.next();
    }

    return Some(last);
  }
}

length no setter override

int get length

The number of elements in this sequence.

Implementation
dart
@override
int get length => _numRangeElements;

nonEmpty no setter inherited

bool get nonEmpty

Whether this collection contains at least one element.

Inherited from RIterableOnce.

Implementation
dart
bool get nonEmpty => !isEmpty;

runtimeType no setter inherited

Type get runtimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
dart
external Type get runtimeType;

size no setter inherited

int get size

Returns the number of elements in this collection.

Inherited from RSeq.

Implementation
dart
@override
int get size => length;

start final

final int start

The first value in the range.

Implementation
dart
final int start;

step final

final int step

The increment between successive elements.

Implementation
dart
final int step;

tail no setter override

Range get tail

Returns a new collection with the first element removed. If this collection is empty, an empty collection is returned.

Implementation
dart
@override
Range get tail {
  if (isEmpty) throw _emptyRangeError("tail");
  if (_numRangeElements == 1) {
    return _newEmptyRange(end);
  } else if (isInclusive) {
    return Range.inclusive(start + step, end, step);
  } else {
    return Range.exclusive(start + step, end, step);
  }
}

tails no setter override

RIterator<Range> get tails

Returns an iterator of all potential tails of this collection, starting with the entire collection and ending with an empty one.

Implementation
dart
@override
RIterator<Range> get tails => _RangeTailsIterator(this);

Methods

appended() inherited

IndexedSeq<int> appended(int elem)

Returns a new Seq, with the given elem added to the end.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> appended(A elem) => iseqviews.Appended(this, elem);

appendedAll() inherited

IndexedSeq<int> appendedAll(RIterableOnce<int> suffix)

Returns a new Seq, with elems added to the end.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> appendedAll(RIterableOnce<A> suffix) =>
    iseqviews.Concat(this, suffix.toIndexedSeq());

by()

Range by(int step)

Returns a copy of this range with the given step.

Implementation
dart
Range by(int step) => _copy(step: step);

canEqual() inherited

bool canEqual(Object other)

Inherited from IndexedSeq.

Implementation
dart
@override
bool canEqual(Object other) => switch (other) {
  final RSeq<A> that => length == that.length && super.canEqual(that),
  _ => super.canEqual(other),
};

collect() inherited

IndexedSeq<B> collect<B>(Option<B> Function(int) f)

Returns a new collection by applying f to each element an only keeping results of type Some.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<B> collect<B>(Function1<A, Option<B>> f) => super.collect(f).toIndexedSeq();

collectFirst() inherited

Option<B> collectFirst<B>(Option<B> Function(int) f)

Applies f to each element of this collection, returning the first element that results in a Some, if any.

Inherited from RIterableOnce.

Implementation
dart
Option<B> collectFirst<B>(Function1<A, Option<B>> f) {
  final it = iterator;

  while (it.hasNext) {
    final x = f(it.next());
    if (x.isDefined) return x;
  }

  return none();
}

combinations() inherited

RIterator<IndexedSeq<int>> combinations(int n)

Returns an Iterator that will produce all combinations of elements from this sequence of size n in order.

Given the list [1, 2, 2, 2], combinations of size 2 would result in [1, 2] and [2, 2]. Note that [2, 1] would not be included since combinations are taken from element in order.

Also note from the example above, [1, 2] would only be included once even though there are technically 3 ways to generate a combination of [1, 2], only one will be included in the result since the other 2 are duplicates.

Inherited from IndexedSeq.

Implementation
dart
@override
RIterator<IndexedSeq<A>> combinations(int n) =>
    super.combinations(n).map((a) => a.toIndexedSeq());

concat() inherited

IndexedSeq<int> concat(RIterableOnce<int> suffix)

Returns a copy of this collection, with elems added to the end.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> concat(RIterableOnce<A> suffix) => iseqviews.Concat(this, suffix.toIndexedSeq());

contains() override

bool contains(int elem)

Returns true, if any element of this collection equals elem.

Implementation
dart
@override
bool contains(int elem) {
  if (elem == end && !isInclusive) {
    return false;
  } else if (step > 0) {
    if (elem < start || elem > end) {
      return false;
    } else {
      return (step == 1) || (elem - start) % step == 0;
    }
  } else {
    if (elem < end || elem > start) {
      return false;
    } else {
      return (step == -1) || (start - elem) % -step == 0;
    }
  }
}

containsSlice() inherited

bool containsSlice(RSeq<int> that)

Returns true if that is contained in this collection, in order.

Inherited from RSeq.

Implementation
dart
bool containsSlice(RSeq<A> that) => indexOfSlice(that).isDefined;

copyToArray() inherited

int copyToArray(Array<int> xs, [int start = 0, int? n])

Copies elements into xs starting at start, writing at most n elements (or all remaining capacity when n is omitted).

Returns the number of elements actually copied.

Inherited from RIterableOnce.

Implementation
dart
int copyToArray(Array<A> xs, [int start = 0, int? n]) {
  final it = iterator;
  final end = start + min(n ?? Integer.maxValue, xs.length - start);
  var i = start;

  while (i < end && it.hasNext) {
    xs[i] = it.next();
    i += 1;
  }

  return i - start;
}

corresponds() inherited

bool corresponds<B>(RIterable<B> that, bool Function(int, B) p)

Returns true if this collection has the same size as that and each corresponding element from this and that satisfies the given predicate p.

Inherited from RIterableOnce.

Implementation
dart
bool corresponds<B>(
  covariant RIterable<B> that,
  Function2<A, B, bool> p,
) {
  final a = iterator;
  final b = that.iterator;

  while (a.hasNext && b.hasNext) {
    if (!p(a.next(), b.next())) return false;
  }

  return !a.hasNext && !b.hasNext;
}

count() inherited

int count(bool Function(int) p)

Return the number of elements in this collection that satisfy the given predicate.

Inherited from RIterableOnce.

Implementation
dart
int count(Function1<A, bool> p) {
  var res = 0;
  final it = iterator;

  while (it.hasNext) {
    if (p(it.next())) res += 1;
  }

  return res;
}

diff() inherited

IndexedSeq<int> diff(RSeq<int> that)

Returns a new collection with the difference of this and that, i.e. all elements that appear in only this collection.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> diff(RSeq<A> that) => super.diff(that).toIndexedSeq();

distinct() override

Range distinct()

Returns a new collection where every element is distinct according to equality.

Implementation
dart
@override
Range distinct() => this;

distinctBy() inherited

IndexedSeq<int> distinctBy<B>(B Function(int) f)

Returns a new collection where every element is distinct according to the application of f to each element.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> distinctBy<B>(Function1<A, B> f) => super.distinctBy(f).toIndexedSeq();

drop() override

Range drop(int n)

Returns a new collection with the first n elements removed.

Implementation
dart
@override
Range drop(int n) {
  if (n <= 0 || isEmpty) {
    return this;
  } else if (n >= _numRangeElements && _numRangeElements >= 0) {
    return _newEmptyRange(end);
  } else {
    &#47;&#47; May have more than Int.MaxValue elements (numRangeElements < 0)
    &#47;&#47; but the logic is the same either way: go forwards n steps, keep the rest
    return _copy(start: _locationAfterN(n));
  }
}

dropRight() override

Range dropRight(int n)

Return a new collection with the last n elements removed.

Implementation
dart
@override
Range dropRight(int n) {
  if (n <= 0) {
    return this;
  } else if (_numRangeElements >= 0) {
    return take(_numRangeElements - n);
  } else {
    &#47;&#47; Need to handle over-full range separately
    final y = last - step * n;
    if ((step > 0 && y < start) || (step < 0 && y > start)) {
      return _newEmptyRange(start);
    } else {
      return Range.inclusive(start, y, step);
    }
  }
}

dropWhile() override

Range dropWhile(bool Function(int) p)

Returns a new collection with leading elements satisfying p removed.

Implementation
dart
@override
Range dropWhile(Function1<int, bool> p) {
  final stop = _argTakeWhile(p);
  if (stop == start) {
    return this;
  } else {
    final x = stop - step;
    if (x == last) {
      return _newEmptyRange(last);
    } else {
      return Range.inclusive(x + step, last, step);
    }
  }
}

endsWith() inherited

bool endsWith(RIterable<int> that)

Returns true if the end of this collection has the same elements in order as that. Otherwise, false is returned.

Inherited from RSeq.

Implementation
dart
bool endsWith(RIterable<A> that) {
  if (that.isEmpty) {
    return true;
  } else {
    final i = iterator.drop(length - that.size);
    final j = that.iterator;
    while (i.hasNext && j.hasNext) {
      if (i.next() != j.next()) return false;
    }

    return !j.hasNext;
  }
}

exclusive()

Range exclusive()

Returns a half-open (exclusive) version of this range.

Returns this if already exclusive.

Implementation
dart
Range exclusive() => !isInclusive ? this : Range.exclusive(start, end, step);

exists() inherited

bool exists(bool Function(int) p)

Returns true if any element of this collection satisfies the given predicate, false if no elements satisfy it.

Inherited from RIterableOnce.

Implementation
dart
bool exists(Function1<A, bool> p) {
  var res = false;
  final it = iterator;

  while (!res && it.hasNext) {
    res = p(it.next());
  }

  return res;
}

filter() inherited

IndexedSeq<int> filter(bool Function(int) p)

Returns a new collection containing only elements that satisfy p.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> filter(Function1<A, bool> p) => super.filter(p).toIndexedSeq();

filterNot() inherited

IndexedSeq<int> filterNot(bool Function(int) p)

Returns a new collection containing only elements that do not satisfy p.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> filterNot(Function1<A, bool> p) => super.filterNot(p).toIndexedSeq();

find() inherited

Option<int> find(bool Function(int) p)

Returns the first element from this collection that satisfies the given predicate p. If no element satisfies p, None is returned.

Inherited from RIterableOnce.

Implementation
dart
Option<A> find(Function1<A, bool> p) {
  final it = iterator;

  while (it.hasNext) {
    final a = it.next();
    if (p(a)) return Some(a);
  }

  return none();
}

findLast() inherited

Option<int> findLast(bool Function(int) p)

Returns the last element satisfying p as Some, or None if none.

Inherited from RSeq.

Implementation
dart
Option<A> findLast(Function1<A, bool> p) {
  final it = reverseIterator();
  while (it.hasNext) {
    final elem = it.next();
    if (p(elem)) return Some(elem);
  }

  return none();
}

flatMap() inherited

IndexedSeq<B> flatMap<B>(RIterableOnce<B> Function(int) f)

Returns a new collection by applying f to each element and concatenating the results.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<B> flatMap<B>(Function1<A, RIterableOnce<B>> f) => super.flatMap(f).toIndexedSeq();

fold() inherited

int fold(int init, int Function(int, int) op)

Alias for foldLeft with a same-type accumulator.

Inherited from RIterable.

Implementation
dart
A fold(A init, Function2<A, A, A> op) => foldLeft(init, op);

foldLeft() inherited

B foldLeft<B>(B z, B Function(B, int) op)

Returns a summary value by applying op to all elements of this collection, moving from left to right. The fold uses a seed value of z.

Inherited from RIterableOnce.

Implementation
dart
B foldLeft<B>(B z, Function2<B, A, B> op) {
  var result = z;
  final it = iterator;

  while (it.hasNext) {
    result = op(result, it.next());
  }

  return result;
}

foldRight() inherited

B foldRight<B>(B z, B Function(int, B) op)

Returns a summary value by applying op to all elements of this collection, moving from right to left. The fold uses a seed value of z.

Inherited from RIterableOnce.

Implementation
dart
B foldRight<B>(B z, Function2<A, B, B> op) => _reversed().foldLeft(z, (b, a) => op(a, b));

forall() inherited

bool forall(bool Function(int) p)

Returns true if all elements of this collection satisfy the given predicate, false if any elements do not.

Inherited from RIterableOnce.

Implementation
dart
bool forall(Function1<A, bool> p) {
  var res = true;
  final it = iterator;

  while (res && it.hasNext) {
    res = p(it.next());
  }

  return res;
}

foreach() inherited

void foreach<U>(U Function(int) f)

Applies f to each element of this collection, discarding any resulting values.

Inherited from RIterableOnce.

Implementation
dart
void foreach<U>(Function1<A, U> f) {
  final it = iterator;
  while (it.hasNext) {
    f(it.next());
  }
}

groupBy() inherited

IMap<K, IndexedSeq<int>> groupBy<K>(K Function(int) f)

Partitions all elements of this collection by applying f to each element and accumulating duplicate keys in the returned IMap.

Inherited from IndexedSeq.

Implementation
dart
@override
IMap<K, IndexedSeq<A>> groupBy<K>(Function1<A, K> f) =>
    super.groupBy(f).mapValues((a) => a.toIndexedSeq());

grouped() override

RIterator<Range> grouped(int size)

Returns a new iterator where each element is a collection of size elements from the original collection. The last element may contain less than size elements.

Implementation
dart
@override
RIterator<Range> grouped(int size) => _RangeGroupedIterator(this, size);

groupMap() inherited

IMap<K, IndexedSeq<B>> groupMap<K, B>(K Function(int) key, B Function(int) f)

Creates a new map by generating a key-value pair for each elements of this collection using key and f. Any elements that generate the same key will have the resulting values accumulated in the returned map.

Inherited from IndexedSeq.

Implementation
dart
@override
IMap<K, IndexedSeq<B>> groupMap<K, B>(Function1<A, K> key, Function1<A, B> f) =>
    super.groupMap(key, f).mapValues((a) => a.toIndexedSeq());

groupMapReduce() inherited

IMap<K, B> groupMapReduce<K, B>(
  K Function(int) key,
  B Function(int) f,
  B Function(B, B) reduce,
)

Partitions all elements of this collection by applying key to each element. Additionally f is applied to each element to generate a value. If multiple values are generating for the same key, those values will be combined using reduce.

Inherited from RIterable.

Implementation
dart
IMap<K, B> groupMapReduce<K, B>(
  Function1<A, K> key,
  Function1<A, B> f,
  Function2<B, B, B> reduce,
) {
  final m = <K, B>{};

  foreach((elem) {
    m.update(key(elem), (b) => reduce(b, f(elem)), ifAbsent: () => f(elem));
  });

  return IMap.fromDart(m);
}

inclusive()

Range inclusive()

Returns a closed (inclusive) version of this range.

Returns this if already inclusive.

Implementation
dart
Range inclusive() => isInclusive ? this : Range.inclusive(start, end, step);

indexOf() override

Option<int> indexOf(int elem, [int from = 0])

Returns the first index, if any, where the element at that index equals elem. If no index contains elem, None is returned.

Implementation
dart
@override
Option<int> indexOf(int elem, [int from = 0]) {
  final pos = _posOf(elem);
  return Option.when(() => 0 <= pos && from <= pos, () => pos);
}

indexOfSlice() inherited

Option<int> indexOfSlice(RSeq<int> that, [int from = 0])

Finds the first index in this collection where the next sequence of elements is equal to that. If that cannot be found in this collection, None is returned.

Inherited from RSeq.

Implementation
dart
Option<int> indexOfSlice(RSeq<A> that, [int from = 0]) {
  if (that.isEmpty && from == 0) {
    return const Some(0);
  } else {
    final l = knownSize;
    final tl = that.knownSize;

    if (l >= 0 && tl >= 0) {
      final clippedFrom = max(0, from);
      if (from > l) {
        return none();
      } else if (tl < 1) {
        return Some(clippedFrom);
      } else if (l < tl) {
        return none();
      } else {
        return _kmpSearch(this, clippedFrom, l, that, 0, tl, true);
      }
    } else {
      var i = from;
      var s = drop(i);
      while (s.nonEmpty) {
        if (s.startsWith(that)) return Some(i);

        i += 1;
        s = s.tail;
      }
      return none();
    }
  }
}

indexWhere() inherited

Option<int> indexWhere(bool Function(int) p, [int from = 0])

Returns the index of the first element that satisfies the predicate p. If no element satisfies, None is returned.

Inherited from RSeq.

Implementation
dart
Option<int> indexWhere(Function1<A, bool> p, [int from = 0]) => iterator.indexWhere(p, from);

indices() inherited

Range indices()

Returns a range of all indices of this sequence

Will force evaluation.

Inherited from RSeq.

Implementation
dart
Range indices() => Range.exclusive(0, length);

intersect() inherited

IndexedSeq<int> intersect(RSeq<int> that)

Returns a new collection with the intersection of this and that, i.e. all elements that appear in both collections.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> intersect(RSeq<A> that) => super.intersect(that).toIndexedSeq();

intersperse() inherited

IndexedSeq<int> intersperse(int x)

Returns a new collection with sep inserted between each element.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> intersperse(A x) => super.intersperse(x).toIndexedSeq();

isDefinedAt() inherited

bool isDefinedAt(int idx)

Returns true if this collection has an element at the given idx.

Inherited from RSeq.

Implementation
dart
bool isDefinedAt(int idx) => 0 <= idx && idx < size;

lastIndexOf() override

Option<int> lastIndexOf(int elem, [int end = 2147483647])

Returns the last index, if any, where the element at that index equals elem. If no index contains elem, None is returned.

Implementation
dart
@override
Option<int> lastIndexOf(int elem, [int end = 2147483647]) {
  final pos = _posOf(elem);
  return Option.when(() => 0 <= pos && pos <= end, () => pos);
}

lastIndexOfSlice() inherited

Option<int> lastIndexOfSlice(RSeq<int> that, [int end = 2147483647])

Finds the last index in this collection where the next sequence of elements is equal to that. If that cannot be found in this collection, None is returned.

Inherited from RSeq.

Implementation
dart
Option<int> lastIndexOfSlice(RSeq<A> that, [int end = 2147483647]) {
  final l = length;
  final tl = that.length;
  final clippedL = min(l - tl, end);

  if (end < 0) {
    return none();
  } else if (tl < 1) {
    return Some(clippedL);
  } else if (l < tl) {
    return none();
  } else {
    return _kmpSearch(this, 0, clippedL + tl, that, 0, tl, false);
  }
}

lastIndexWhere() inherited

Option<int> lastIndexWhere(bool Function(int) p, [int end = 2147483647])

Returns the index of the last element that satisfies the predicate p. If no element satisfies, None is returned.

Inherited from RSeq.

Implementation
dart
Option<int> lastIndexWhere(Function1<A, bool> p, [int end = 2147483647]) {
  var i = length - 1;
  final it = reverseIterator();

  while (it.hasNext) {
    final elem = it.next();

    if (i < end && p(elem)) return Some(i);

    i -= 1;
  }

  return none();
}

lift() inherited

Option<int> lift(int ix)

Returns the element at index ix as a Some. If ix is outside the range of this collection, None is returned.

Inherited from RSeq.

Implementation
dart
Option<A> lift(int ix) => Option.when(() => isDefinedAt(ix), () => this[ix]);

map() override

IndexedSeq<B> map<B>(B Function(int) f)

Returns a new collection by applying f to each element.

Implementation
dart
@override
IndexedSeq<B> map<B>(Function1<int, B> f) {
  _validateMaxLength();
  return super.map(f).toIndexedSeq();
}

maxByOption() inherited

Option<int> maxByOption<B>(B Function(int) f, Order<B> order)

Finds the largest element in this collection by applying f to each element and using the given Order to find the greatest.

If this collection is empty, None is returned.

Inherited from RIterableOnce.

Implementation
dart
Option<A> maxByOption<B>(Function1<A, B> f, Order<B> order) => _minMaxByOption(f, order.max);

maxOption() inherited

Option<int> maxOption(Order<int> order)

Finds the largest element in this collection according to the given Order.

If this collection is empty, None is returned.

Inherited from RIterableOnce.

Implementation
dart
Option<A> maxOption(Order<A> order) => switch (knownSize) {
  0 => none(),
  _ => _reduceOptionIterator(iterator, order.max),
};

minByOption() inherited

Option<int> minByOption<B>(B Function(int) f, Order<B> order)

Finds the smallest element in this collection by applying f to each element and using the given Order to find the greatest.

If this collection is empty, None is returned.

Inherited from RIterableOnce.

Implementation
dart
Option<A> minByOption<B>(Function1<A, B> f, Order<B> order) => _minMaxByOption(f, order.min);

minOption() inherited

Option<int> minOption(Order<int> order)

Finds the largest element in this collection according to the given Order.

If this collection is empty, None is returned.

Inherited from RIterableOnce.

Implementation
dart
Option<A> minOption(Order<A> order) => switch (knownSize) {
  0 => none(),
  _ => _reduceOptionIterator(iterator, order.min),
};

mkString() inherited

String mkString({String? start, String? sep, String? end})

Returns a String by using each elements toString(), adding sep between each element. If start is defined, it will be prepended to the resulting string. If end is defined, it will be appended to the resulting string.

Inherited from RIterableOnce.

Implementation
dart
String mkString({String? start, String? sep, String? end}) {
  if (knownSize == 0) {
    return '${start ?? ""}${end ?? ""}';
  } else {
    return _mkStringImpl(StringBuffer(), start ?? '', sep ?? '', end ?? '');
  }
}

noSuchMethod() inherited

dynamic noSuchMethod(Invocation invocation)

Invoked when a nonexistent method or property is accessed.

A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:

dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time error

This invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).

Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.

A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:

dart
class MockList<T> implements List<T> {
  noSuchMethod(Invocation invocation) {
    log(invocation);
    super.noSuchMethod(invocation); // Will throw.
  }
}
void main() {
  MockList().add(42);
}

This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.

If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.

The default behavior is to throw a NoSuchMethodError.

Inherited from Object.

Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);

padTo() inherited

IndexedSeq<int> padTo(int len, int elem)

Returns a new collection with a length of at least len.

If this collection is shorter than len, the returned collection will have size len and elem will be used for each new element needed to reach that size.

If this collection is already at least len in size, this collection will be returned.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> padTo(int len, A elem) => super.padTo(len, elem).toIndexedSeq();

partition() inherited

Record partition(bool Function(int) p)

Returns 2 collections as a tuple where the first tuple element will be a collection of elements that satisfy the given predicate p. The second item of the returned tuple will be elements that do not satisfy p.

Inherited from IndexedSeq.

Implementation
dart
@override
(IndexedSeq<A>, IndexedSeq<A>) partition(Function1<A, bool> p) {
  final (a, b) = super.partition(p);
  return (a.toIndexedSeq(), b.toIndexedSeq());
}

partitionMap() inherited

Record partitionMap<A1, A2>(Either<A1, A2> Function(int) f)

Applies f to each element of this collection and returns a separate collection for all applications resulting in a Left and Right respectively.

Inherited from IndexedSeq.

Implementation
dart
@override
(IndexedSeq<A1>, IndexedSeq<A2>) partitionMap<A1, A2>(Function1<A, Either<A1, A2>> f) {
  final (a, b) = super.partitionMap(f);
  return (a.toIndexedSeq(), b.toIndexedSeq());
}

patch() inherited

IndexedSeq<int> patch(int from, RIterableOnce<int> other, int replaced)

Returns a new collection with replaced elements starting at from replaced by the elements of other.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> patch(int from, RIterableOnce<A> other, int replaced) =>
    super.patch(from, other, replaced).toIndexedSeq();

permutations() inherited

RIterator<IndexedSeq<int>> permutations()

Returns an Iterator that will emit all possible permutations of the elements in this collection.

Note that only distinct permutations are emitted. Given the example [1, 2, 2, 2] the permutations will only include [1, 2, 2, 2] once, even though there are 3 different way to generate that permutation.

Inherited from IndexedSeq.

Implementation
dart
@override
RIterator<IndexedSeq<A>> permutations() => super.permutations().map((a) => a.toIndexedSeq());

prepended() inherited

IndexedSeq<int> prepended(int elem)

Returns a new collection with elem added to the beginning.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> prepended(A elem) => super.prepended(elem).toIndexedSeq();

prependedAll() inherited

IndexedSeq<int> prependedAll(RIterableOnce<int> prefix)

Returns a new collection with all elems added to the beginning.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> prependedAll(RIterableOnce<A> prefix) => super.prependedAll(prefix).toIndexedSeq();

reduce() inherited

int reduce(int Function(int, int) op)

Reduces this collection to a single value by applying op left to right.

Throws if the collection is empty.

Inherited from RIterableOnce.

Implementation
dart
A reduce(Function2<A, A, A> op) => reduceLeft(op);

reduceLeft() inherited

int reduceLeft(int Function(int, int) op)

Reduces from left to right. Throws if empty.

Inherited from RIterableOnce.

Implementation
dart
A reduceLeft(Function2<A, A, A> op) => switch (this) {
  final IndexedSeq<A> seq when seq.length > 0 => _foldl(seq, 1, seq[0], op),
  _ when knownSize == 0 => throw UnsupportedError('empty.reduceLeft'),
  _ => _reduceLeftIterator(() => throw UnsupportedError('empty.reduceLeft'), op),
};

reduceLeftOption() inherited

Option<int> reduceLeftOption(int Function(int, int) op)

Returns a summary values of all elements of this collection by applying f to each element, moving left to right.

If this collection is empty, None will be returned.

Inherited from RIterableOnce.

Implementation
dart
Option<A> reduceLeftOption(Function2<A, A, A> op) => switch (knownSize) {
  0 => none(),
  _ => _reduceOptionIterator(iterator, op),
};

reduceOption() inherited

Option<int> reduceOption(int Function(int, int) op)

Returns a summary values of all elements of this collection by applying f to each element, moving left to right.

If this collection is empty, None will be returned.

Inherited from RIterableOnce.

Implementation
dart
Option<A> reduceOption(Function2<A, A, A> op) => reduceLeftOption(op);

reduceRight() inherited

int reduceRight(int Function(int, int) op)

Reduces from right to left. Throws if empty.

Inherited from RIterableOnce.

Implementation
dart
A reduceRight(Function2<A, A, A> op) => switch (this) {
  final IndexedSeq<A> seq when seq.length > 0 => _foldr(seq, op),
  _ when knownSize == 0 => throw UnsupportedError('empty.reduceLeft'),
  _ => _reversed().reduceLeft((x, y) => op(y, x)),
};

reduceRightOption() inherited

Option<int> reduceRightOption(int Function(int, int) op)

Returns a summary values of all elements of this collection by applying f to each element, moving right to left.

If this collection is empty, None will be returned.

Inherited from RIterableOnce.

Implementation
dart
Option<A> reduceRightOption(Function2<A, A, A> op) => switch (knownSize) {
  -1 => _reduceOptionIterator(_reversed().iterator, (x, y) => op(y, x)),
  0 => none(),
  _ => Some(reduceRight(op)),
};

removeAt() inherited

RSeq<int> removeAt(int idx)

Returns a new collection with the element at idx removed.

Throws RangeError if idx is out of bounds.

Inherited from RSeq.

Implementation
dart
RSeq<A> removeAt(int idx) {
  if (0 <= idx && idx < length) {
    if (idx == 0) {
      return tail;
    } else {
      final (a, b) = splitAt(idx);
      return a.concat(b.tail);
    }
  } else {
    throw RangeError('$idx is out of bounds (min 0, max ${length - 1})');
  }
}

reverse() override

IndexedSeq<int> reverse()

Returns a new collection with the order of the elements reversed.

Implementation
dart
@override
IndexedSeq<int> reverse() => isEmpty ? this : Range.inclusive(last, start, -step);

reverseIterator() inherited

RIterator<int> reverseIterator()

Returns an iterator that will emit all elements in this collection, in reverse order.

Inherited from RSeq.

Implementation
dart
RIterator<A> reverseIterator() => reverse().iterator;

sameElements() override

bool sameElements(RIterable<int> that)

Returns true if this collection has the same elements, in the same order, as that.

Implementation
dart
@override
bool sameElements(RIterable<int> that) {
  if (that is Range) {
    return switch (length) {
      0 => that.isEmpty,
      1 => that.length == 1 && start == that.start,
      final n => that.length == n && (start == that.start && step == that.step),
    };
  } else {
    return super.sameElements(that);
  }
}

scan() inherited

IndexedSeq<B> scan<B>(B z, B Function(B, int) op)

Alias for scanLeft.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<B> scan<B>(B z, Function2<B, A, B> op) => super.scan(z, op).toIndexedSeq();

scanLeft() inherited

IndexedSeq<B> scanLeft<B>(B z, B Function(B, int) op)

Returns a new collection of running totals starting with z.

The first element of the result is z; each subsequent element is the result of applying op to the previous total and the next element.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<B> scanLeft<B>(B z, Function2<B, A, B> op) => super.scanLeft(z, op).toIndexedSeq();

scanRight() inherited

IndexedSeq<B> scanRight<B>(B z, B Function(int, B) op)

Returns a new collection of running totals starting with z, traversing from right to left.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<B> scanRight<B>(B z, Function2<A, B, B> op) => super.scanRight(z, op).toIndexedSeq();

segmentLength() inherited

int segmentLength(bool Function(int) p, [int from = 0])

Returns the length of the longest prefix starting at from where every element satisfies p.

Inherited from RSeq.

Implementation
dart
int segmentLength(Function1<A, bool> p, [int from = 0]) {
  var i = 0;
  final it = iterator.drop(from);

  while (it.hasNext && p(it.next())) {
    i += 1;
  }

  return i;
}

slice() override

Range slice(int from, int until)

Returns a new collection containing elements in the range [from, until).

Implementation
dart
@override
Range slice(int from, int until) {
  if (from <= 0) {
    return take(until);
  } else if (until >= _numRangeElements && _numRangeElements >= 0) {
    return drop(from);
  } else {
    final fromValue = _locationAfterN(from);
    if (from >= until) {
      return _newEmptyRange(fromValue);
    } else {
      return Range.inclusive(fromValue, _locationAfterN(until - 1), step);
    }
  }
}

sliding() inherited

RIterator<IndexedSeq<int>> sliding(int size, [int step = 1])

Returns an iterator where elements are fixed size chunks of size n of the original collection. Each chunk is calculated by sliding a 'window' of size n over the original collection, moving the window step elements at a time.

Inherited from IndexedSeq.

Implementation
dart
@override
RIterator<IndexedSeq<A>> sliding(int size, [int step = 1]) =>
    super.sliding(size, step).map((a) => a.toIndexedSeq());

sortBy() inherited

IndexedSeq<int> sortBy<B>(Order<B> order, B Function(int) f)

Returns a new collection that is sorted according to order after applying f to each element in this collection.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> sortBy<B>(Order<B> order, Function1<A, B> f) =>
    super.sortBy(order, f).toIndexedSeq();

sorted() override

IndexedSeq<int> sorted(Order<int> order)

Returns a new collection that is sorted according to order.

Implementation
dart
@override
IndexedSeq<int> sorted(Order<int> order) {
  if (order == Order.ints) {
    if (step > 0) {
      return this;
    } else {
      return reverse();
    }
  } else {
    return super.sorted(order).toIndexedSeq();
  }
}

sortWith() inherited

IndexedSeq<int> sortWith(bool Function(int, int) lt)

Returns a new collection sorted using the provided function lt which is used to determine if one element is less than the other.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<A> sortWith(Function2<A, A, bool> lt) => super.sortWith(lt).toIndexedSeq();

span() override

Record span(bool Function(int) p)

Returns two collections: elements before and starting from the first element that does not satisfy p.

Implementation
dart
@override
(Range, Range) span(Function1<int, bool> p) {
  final border = _argTakeWhile(p);
  if (border == start) {
    return (_newEmptyRange(start), this);
  } else {
    final x = border - step;
    if (x == last) {
      return (this, _newEmptyRange(last));
    } else {
      return (Range.inclusive(start, x, step), Range.inclusive(x + step, last, step));
    }
  }
}

splitAt() override

Record splitAt(int n)

Returns two collections: the first n elements and the remainder.

Implementation
dart
@override
(Range, Range) splitAt(int n) => (take(n), drop(n));

startsWith() inherited

bool startsWith(RIterableOnce<int> that, [int offset = 0])

Returns true if the beginning of this collection corresponds with that.

Inherited from RSeq.

Implementation
dart
bool startsWith(RIterableOnce<A> that, [int offset = 0]) {
  final i = iterator.drop(offset);
  final j = that.iterator;
  while (j.hasNext && i.hasNext) {
    if (i.next() != j.next()) return false;
  }

  return !j.hasNext;
}

take() override

Range take(int n)

Returns a new collection containing only the first n elements.

Implementation
dart
@override
Range take(int n) {
  if (n <= 0 || isEmpty) {
    return _newEmptyRange(start);
  } else if (n >= _numRangeElements && _numRangeElements >= 0) {
    return this;
  } else {
    &#47;&#47; May have more than Int.MaxValue elements in range (numRangeElements < 0)
    &#47;&#47; but the logic is the same either way: take the first n
    return Range.inclusive(start, _locationAfterN(n - 1), step);
  }
}

takeRight() override

Range takeRight(int n)

Returns a new collection with the last n elements of this collection. If n is greater than the size of this collection, the original collection is returned.

Implementation
dart
@override
Range takeRight(int n) {
  if (n <= 0) {
    return _newEmptyRange(start);
  } else if (_numRangeElements >= 0) {
    return drop(_numRangeElements - n);
  } else {
    &#47;&#47; Need to handle over-full range separately
    final y = last;
    final x = y - step * (n - 1);

    if ((step > 0 && x < start) || (step < 0 && x > start)) {
      return this;
    } else {
      return Range.inclusive(x, y, step);
    }
  }
}

takeWhile() override

Range takeWhile(bool Function(int) p)

Returns a new collection of leading elements that satisfy p.

Implementation
dart
@override
Range takeWhile(Function1<int, bool> p) {
  final stop = _argTakeWhile(p);
  if (stop == start) {
    return _newEmptyRange(start);
  } else {
    final x = stop - step;
    if (x == last) {
      return this;
    } else {
      return Range.inclusive(start, x, step);
    }
  }
}

tapEach() override

Range tapEach<U>(U Function(int) f)

Applies f to each element in this collection, discarding any results and returns this collection.

Implementation
dart
@override
Range tapEach<U>(Function1<int, U> f) {
  foreach(f);
  return this;
}

toIList() inherited

IList<int> toIList()

Returns an IList with the same elements as this collection.

Inherited from RIterableOnce.

Implementation
dart
IList<A> toIList() => IList.from(this);

toIndexedSeq() inherited

IndexedSeq<int> toIndexedSeq()

Returns an IndexedSeq with the same elements as this collection.

Inherited from RIterableOnce.

Implementation
dart
IndexedSeq<A> toIndexedSeq() => IndexedSeq.from(this);

toISet() inherited

ISet<int> toISet()

Returns an ISet with the same elements as this collection, duplicates removed.

Inherited from RIterableOnce.

Implementation
dart
ISet<A> toISet() => ISet.from(this);

toIVector() inherited

IVector<int> toIVector()

Returns an IVector with the same elements as this collection.

Inherited from RIterableOnce.

Implementation
dart
IVector<A> toIVector() => IVector.from(this);

toList() inherited

List<int> toList({bool growable = true})

Returns a new List with the same elements as this collection.

Inherited from RIterableOnce.

Implementation
dart
List<A> toList({bool growable = true}) {
  if (growable) {
    final it = iterator;
    final res = List<A>.empty(growable: true);

    while (it.hasNext) {
      res.add(it.next());
    }

    return res;
  } else {
    final it = iterator;
    return List.generate(size, (_) => it.next());
  }
}

toSeq() inherited

RSeq<int> toSeq()

Returns a RSeq with the same elements as this collection.

Inherited from RIterableOnce.

Implementation
dart
RSeq<A> toSeq() => RSeq.from(this);

toString() override

String toString()

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Implementation
dart
@override
String toString() {
  final preposition = isInclusive ? 'to' : 'until';
  final stepped = step == 1 ? '' : ' by $step';
  final prefix =
      isEmpty
          ? 'empty '
          : !_isExact
          ? 'inexact '
          : '';
  return '${prefix}Range $start $preposition $end$stepped';
}

traverseEither() inherited

Either<B, RSeq<C>> traverseEither<B, C>(Either<B, C> Function(int) f)

Applies f to each element of this RSeq and collects the results into a new collection. If Left is encountered for any element, that result is returned and any additional elements will not be evaluated.

Inherited from RSeq.

Implementation
dart
Either<B, RSeq<C>> traverseEither<B, C>(Function1<A, Either<B, C>> f) {
  Either<B, RSeq<C>> result = Either.pure(IVector.empty());

  foreach((elem) {
    &#47;&#47; short circuit
    if (result.isLeft) {
      return result;
    }

    &#47;&#47; Workaround for contravariant issues in error case
    result = result.fold(
      (_) => result,
      (acc) => f(elem).fold(
        (err) => err.asLeft(),
        (a) => acc.appended(a).asRight(),
      ),
    );
  });

  return result;
}

traverseOption() inherited

Option<RSeq<B>> traverseOption<B>(Option<B> Function(int) f)

Applies f to each element of this RSeq and collects the results into a new collection. If None is encountered for any element, that result is returned and any additional elements will not be evaluated.

Inherited from RSeq.

Implementation
dart
Option<RSeq<B>> traverseOption<B>(Function1<A, Option<B>> f) {
  Option<RSeq<B>> result = Option.pure(IVector.empty());

  foreach((elem) {
    if (result.isEmpty) return result; &#47;&#47; short circuit
    result = result.flatMap((l) => f(elem).map((b) => l.appended(b)));
  });

  return result;
}

updated() inherited

RSeq<int> updated(int index, int elem)

Returns a new collection with the element at index replaced by elem.

Throws RangeError if index is out of bounds.

Inherited from RSeq.

Implementation
dart
RSeq<A> updated(int index, A elem) {
  if (index < 0) {
    throw RangeError(
      '$index is out of bounds (min 0, max ${knownSize >= 0 ? knownSize : 'unknown'})',
    );
  }

  final b = IVector.builder<A>();

  var i = 0;
  final it = iterator;

  while (i < index && it.hasNext) {
    b.addOne(it.next());
    i += 1;
  }

  if (!it.hasNext) {
    if (index < 0) {
      throw RangeError('$index is out of bounds (min 0, max ${i - 1})');
    }
  }

  b.addOne(elem);
  it.next();

  while (it.hasNext) {
    b.addOne(it.next());
  }

  return b.result();
}

zip() inherited

IndexedSeq<Record> zip<B>(RIterableOnce<B> that)

Returns a new collection that combines corresponding elements from this collection and that as a tuple. The length of the returned collection will be the minimum of this collections size and the size of that.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<(A, B)> zip<B>(RIterableOnce<B> that) => super.zip(that).toIndexedSeq();

zipAll() inherited

IndexedSeq<Record> zipAll<B>(RIterableOnce<B> that, int thisElem, B thatElem)

Returns a new collection that combines corresponding elements from this collection and that as a tuple. The length of the returned collection will be the maximum of this collections size and thes size of that. If this collection is shorter than that, thisElem will be used to fill in the resulting collection. If that is shorter, thatElem will be used to will in the resulting collection.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<(A, B)> zipAll<B>(RIterableOnce<B> that, A thisElem, B thatElem) =>
    super.zipAll(that, thisElem, thatElem).toIndexedSeq();

zipWithIndex() inherited

IndexedSeq<Record> zipWithIndex()

Return a new collection with each element of this collection paired with it's respective index.

Inherited from IndexedSeq.

Implementation
dart
@override
IndexedSeq<(A, int)> zipWithIndex() => super.zipWithIndex().toIndexedSeq();

Extension Methods

product() extension

int product()

Returns the product of all elements in this list

Available on RIterableOnce<A>, provided by the RIterableIntOps extension

Implementation
dart
int product() {
  var p = 1;
  final it = iterator;

  while (it.hasNext) {
    p *= it.next();
  }

  return p;
}

sum() extension

int sum()

Returns the sum of all elements in this list

Available on RIterableOnce<A>, provided by the RIterableIntOps extension

Implementation
dart
int sum() {
  var s = 0;
  final it = iterator;

  while (it.hasNext) {
    s += it.next();
  }

  return s;
}

Operators

operator ==() override

bool operator ==(Object other)

The equality operator.

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

  • Total: It must return a boolean for all arguments. It should never throw.

  • Reflexive: For all objects o, o == o must be true.

  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.

Implementation
dart
@override
bool operator ==(Object other) {
  if (other is Range) {
    if (isEmpty) {
      return other.isEmpty;
    } else if (other.isEmpty) {
      return false;
    } else {
      return (start == other.start) &&
          (last == other.last) &&
          (start == last || step == other.step);
    }
  } else {
    return super == other;
  }
}

operator override

int operator [](int idx)

Returns the element at index idx.

Implementation
dart
@override
int operator [](int idx) {
  _validateMaxLength();
  if (0 <= idx && idx < _numRangeElements) {
    return start + (step * idx);
  } else {
    throw RangeError('$idx is out of bound (min 0, max ${_numRangeElements - 1})');
  }
}

Static Methods

elementCount()

int elementCount(int start, int end, int step, {bool isInclusive = false})
Implementation
dart
static int elementCount(
  int start,
  int end,
  int step, {
  bool isInclusive = false,
}) {
  if (step == 0) throw ArgumentError('zero step');

  final bool isEmpty;

  if (start == end) {
    isEmpty = !isInclusive;
  } else if (start < end) {
    isEmpty = step < 0;
  } else {
    isEmpty = step > 0;
  }

  if (isEmpty) {
    return 0;
  } else {
    final gap = end - start;
    final jumps = gap ~&#47; step;

    &#47;&#47; Whether the size of this range is one larger than the
    &#47;&#47; number of full-sized jumps.
    final hasStub = isInclusive || (gap % step != 0);
    final result = jumps + (hasStub ? 1 : 0);

    if (result > Integer.maxValue) {
      return -1;
    } else {
      return result;
    }
  }
}