windowed method

Iterable<List<E>> windowed(
  1. int size, {
  2. int step = 1,
  3. bool partialWindows = false,
})

Returns a new lazy Iterable of windows of the given size sliding along this collection with the given step.

The last list may have less elements than the given size.

Both size and step must be positive and can be greater than the number of elements in this collection.

Implementation

Iterable<List<E>> windowed(
  int size, {
  int step = 1,
  bool partialWindows = false,
}) sync* {
  final gap = step - size;
  if (gap >= 0) {
    var buffer = <E>[];
    var skip = 0;
    for (final element in this) {
      if (skip > 0) {
        skip -= 1;
        continue;
      }
      buffer.add(element);
      if (buffer.length == size) {
        yield buffer;
        buffer = <E>[];
        skip = gap;
      }
    }
    if (buffer.isNotEmpty && (partialWindows || buffer.length == size)) {
      yield buffer;
    }
  } else {
    final buffer = ListQueue<E>(size);
    for (final element in this) {
      buffer.add(element);
      if (buffer.length == size) {
        yield buffer.toList();
        for (var i = 0; i < step; i++) {
          buffer.removeFirst();
        }
      }
    }
    if (partialWindows) {
      while (buffer.length > step) {
        yield buffer.toList();
        for (var i = 0; i < step; i++) {
          buffer.removeFirst();
        }
      }
      if (buffer.isNotEmpty) {
        yield buffer.toList();
      }
    }
  }
}