0

I have some Lists containing only strings, every string has an equal length. I want to convert these lists into a list that must have 4 items on each list.

For ex.

const _a = [
  '0330',
  '0355',
  '0405',
  '0415',
  '0425',
  '0450',
  '0500',
  '0525',
  '0535',
  '0545',
  '0555',
  '0620',
  '0630',
  '0655',
  '0705',
  '0715',
  '0725',
  '0750',
  '0800',
  '0845',
];

The result I want is like this...

const _a = [
  ['0330', '0355', '0405', '0415'],
  ['0425', '0450', '0500', '0525'],
  ['0535', '0545', '0555', '0620'],
  ['0630', '0655', '0705', '0715'],
  ['0725', '0750', '0800', '0845'],
];
Usama Karim
  • 1,100
  • 4
  • 15

1 Answers1

0

run paritition(_a, 4) and get the result

import 'dart:collection';

/// Partitions the input iterable into lists of the specified size.
Iterable<List<T>> partition<T>(Iterable<T> iterable, int size) {
  return iterable.isEmpty ? [] : _Partition<T>(iterable, size);
}

class _Partition<T> extends IterableBase<List<T>> {
  _Partition(this._iterable, this._size) {
    if (_size <= 0) throw ArgumentError(_size);
  }

  final Iterable<T> _iterable;
  final int _size;

  @override
  Iterator<List<T>> get iterator =>
      _PartitionIterator<T>(_iterable.iterator, _size);
}

class _PartitionIterator<T> implements Iterator<List<T>> {
  _PartitionIterator(this._iterator, this._size);

  final Iterator<T> _iterator;
  final int _size;
  List<T>? _current;

  @override
  List<T> get current {
    return _current as List<T>;
  }

  @override
  bool moveNext() {
    var newValue = <T>[];
    var count = 0;
    while (count < _size && _iterator.moveNext()) {
      newValue.add(_iterator.current);
      count++;
    }
    _current = (count > 0) ? newValue : null;
    return _current != null;
  }
}
Usama Karim
  • 1,100
  • 4
  • 15
  • You should at least quote that this code comes from the [quiver](https://github.com/google/quiver-dart/blob/d5e5ddc5d4476cc35f3de9afc49925a7140b88a2/lib/src/iterables/partition.dart) [package](https://pub.dev/packages/quiver) – Mattia Mar 24 '22 at 08:59
  • I was not aware of its source. Thanks for your comment – Usama Karim Mar 25 '22 at 18:54
  • 2
    A shorter version would be `Iterable> partition(List elements, int size) sync* { RangeError.checkValueInInterval(size, 1, null, "size"); for (var i = 0; i < elements.length; i += size) yield [...elements.getRange(i, i + size)]; }`. The one difference is that it takes a `List` as argument, which makes things so much easier. :) – lrn Mar 25 '22 at 20:36