setWhere<K extends Object> method

Iterable<K> setWhere<K extends Object>(
  1. Iterable<T> others, {
  2. required bool test(
    1. T original,
    2. T other
    ),
  3. required K? apply(
    1. T original,
    2. T other
    ),
  4. K? orElse(
    1. T original
    )?,
})

If others is given to Iterable and the return value of test is true, the return value of apply is replaced with the corresponding value of Iterable.

If no element is found in others for which the return value of test is true, it is replaced by the return value of orElse.

If orElse is not given, the element is deleted.

Iterableothersを与え、testの戻り値がtrueになる場合applyの戻り値をIterableの該当値と置き換えます。

testの戻り値がtrueになる要素がothersから見つからなかった場合、orElseの戻り値に置き換えられます。

orElseが与えられていない場合は要素が削除されます。

final colors = <Map<String, dynamic>>[
  {"id": 1, "color": "red"},
  {"id": 2, "color": "green"},
  {"id": 5, "color": "yellow"}
];
final fruits =  <Map<String, dynamic>>[
  {"id": 1, "fruits": "strawberry"},
  {"id": 3, "fruits": "orange"},
  {"id": 5, "fruits": "banana"}
];
final merged = colors.setWhere(
  fruits,
  test: (original, other) => original["id"] == other["id"],
  apply: (original, other) => original..["fruits"] = other["fruits"],
); // [{"id": 1, "color": "red", "fruits": "strawberry"}, {"id": 5, "color": "yellow", "fruits": "banana"}]

Implementation

Iterable<K> setWhere<K extends Object>(
  Iterable<T> others, {
  required bool Function(T original, T other) test,
  required K? Function(T original, T other) apply,
  K? Function(T original)? orElse,
}) {
  final tmp = <K>[];
  for (final original in this) {
    final res = others.firstWhereOrNull((item) => test.call(original, item));
    if (res != null) {
      final applied = apply.call(original, res);
      if (applied != null) {
        tmp.add(applied);
      }
    } else {
      final applied = orElse?.call(original);
      if (applied != null) {
        tmp.add(applied);
      }
    }
  }
  return tmp;
}