elements<T> method

List<T> elements<T>(
  1. List<T> sourceElements, {
  2. int? count,
  3. bool unique = false,
})

Plucks a random subset of elements from the given sourceElements

if count is passed, the resultant list will contain exactly count elements randomly chosen from the passed sourceElements if count is omitted, then a random count will be chosen in the range between 0 (inclusive) and sourceElements.length (exclusive)

setting unique to true will ensure that the generated list will not contain the same source ELEMENT more than once. Note: if the source list contains the same VALUE multiple times, it's possible that each of those would be randomly selected into the returned list.

Implementation

List<T> elements<T>(List<T> sourceElements, {$core.int? count, bool unique = false}) {
  count  ??= integer(sourceElements.length + 1, min: 0); // -- force default even if `null` is explicitly passed

  if (unique) {
    if (count > sourceElements.length) {
      throw ArgumentError('When `unique` is true, the value passed for `count` ($count) may not be greater than the number of source elements (${sourceElements.length})');
    }

    sourceElements = List.from(sourceElements); // -- clone so we don't pop elements off the original
  }

  return List.generate(count, (i) {
    var index   = integer(sourceElements.length);
    T   element = (unique ? sourceElements.removeAt(index) : sourceElements[index]);

    return element;
  });
}