Skip to content

πŸš€[FEATURE]: updateEachItem, removeEachItem operatorsΒ #2395

@kulichkoff

Description

@kulichkoff

Relevant Package

This feature request is for @ngxs/operators

Description

Implement very useful state operators (updateEachItem and removeEachItem) that must change array-like state, taking selector and operatorOrValue arguments.

Describe the problem you are trying to solve

It was unexpected for me that current updateItem and removeItem implementations on selectors change only one state item. I think, updateEach is very useful and I needed to use something like that.

Describe the solution you'd like

I already implemented those operators in my project. I can contribute by myself or you can just take my solution:

export function updateEachItem<T>(
  selector: NoInfer<Predicate<T>>,
  operatorOrValue: NoInfer<T> | NoInfer<StateOperator<T>>
): StateOperator<T[]> {
  return (existing: readonly T[]) => {
    return existing.map((item: T) => {
      if (!selector(item)) {
        return item;
      }

      let value: T = null!;
      const theOperatorOrValue = operatorOrValue as T | StateOperator<T>;
      if (isStateOperator(theOperatorOrValue)) {
        value = theOperatorOrValue(item as ExistingState<T>);
      } else {
        value = theOperatorOrValue;
      }
      return value;
    });
  };
}

export function removeEachItem<T>(
  selector: NoInfer<Predicate<T>>
): StateOperator<T[]> {
  return (existing: readonly T[]) => {
    return existing.filter((item: T) => !selector(item));
  }
}

Describe alternatives you've considered

None.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions