Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: modifyWhere and modifyFirstWhere #117

Open
VKBobyr opened this issue Dec 26, 2020 · 1 comment · May be fixed by #152
Open

Proposal: modifyWhere and modifyFirstWhere #117

VKBobyr opened this issue Dec 26, 2020 · 1 comment · May be fixed by #152

Comments

@VKBobyr
Copy link

VKBobyr commented Dec 26, 2020

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.

@komape
Copy link
Contributor

komape commented May 17, 2021

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants