dartx icon indicating copy to clipboard operation
dartx copied to clipboard

Proposal: modifyWhere and modifyFirstWhere

Open VKBobyr opened this issue 5 years ago • 1 comments

I propose the following modifier functionality:

typedef Modifier<T> = T Function(T val);
typedef ConditionCheck<T> = bool Function(T val);

extension ModificationExtension<T> on Iterable<T> {
  Iterable<T> modifyWhere(
    ConditionCheck<T> shouldModify,
    Modifier<T> modifier,
  ) {
    return map((item) => shouldModify(item) ? modifier(item) : item);
  }

  Iterable<T> modifyFirstWhere(
    ConditionCheck<T> shouldModify,
    Modifier<T> modifier,
  ) {
    bool modified = false;
    return modifyWhere(
      (v) => !modified && shouldModify(v),
      (v) {
        modified = true;
        return modifier(v);
      },
    );
  }
}

void main() {
  final items = [1, 2, 3, 4, 5, 6];

  final a = items.modifyWhere((v) => v < 3, (i) => -i);
  final b = items.modifyFirstWhere((v) => v > 3, (i) => -i);

  print(a); // (-1, -2, 3, 4, 5, 6)
  print(b); // (1, 2, 3, -4, 5, 6)
}

Motivation

Very common operation when modifying certain items in a list.

VKBobyr avatar Dec 26 '20 22:12 VKBobyr

@VKBobyr Seems like you already have the code for that. Why don't you just open a pull request if you have the implementation ready?

komape avatar May 17 '21 10:05 komape