setWhere<K extends Object> method
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.
Iterableにothers
を与え、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;
}