windowed method

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

Returns a sliding window of size over the iterable.

step controls how far the window moves each time (defaults to 1). If partials is true, the final window will be included even if it is smaller than size.

Implementation

List<List<E>> windowed(int size, {int step = 1, bool partials = false}) {
  if (size <= 0) throw ArgumentError('Size must be positive');
  if (step <= 0) throw ArgumentError('Step must be positive');
  final list = toList();
  final windows = <List<E>>[];
  if (list.isEmpty) return windows;

  for (var start = 0; start < list.length; start += step) {
    final end = start + size;
    if (end <= list.length) {
      windows.add(list.sublist(start, end));
    } else if (partials) {
      windows.add(list.sublist(start));
    } else {
      break;
    }
  }

  return windows;
}