insertWhere method

List<T> insertWhere(
  1. T element,
  2. bool test(
    1. T? prev,
    2. T? current,
    3. T? next
    )
)

Inserts element before the first element in List for which the return value of test is true.

List内のtestの戻り値がtrueになった最初の要素の前にelementを挿入します。

final array = [1, 2, 3, 4, 5, 6, 7, 8];
final inserted = array.insertWhere(10, (prev, current, next) => current == 3); // [1, 2, 10, 3, 4, 5, 6, 7, 8];

Implementation

List<T> insertWhere(
  T element,
  bool Function(T? prev, T? current, T? next) test,
) {
  for (int i = length - 1; i >= 0; i--) {
    if (!test(
      i <= 0 ? null : this[i - 1],
      this[i],
      i >= length - 1 ? null : this[i + 1],
    )) {
      continue;
    }
    insert(i, element);
    return this;
  }
  insert(0, element);
  return this;
}