Skip to content

filter on array indices #54

@Clindbergh

Description

@Clindbergh

🚀 Feature request

Current Behavior

Currently a specific number is needed to modify an array element at a specific index.

type User = {
  uuid: string;
  cats: ReadonlyArray<{ uuid: string, likesMice: boolean }>
} 

const _desiredFilter: Optional<
  User,
  ReadonlyArray<Filter>
> = Optic.id<User>().at('user').at('cats').index(2)

In most cases I must find the desired index beforehand, e.g. by iterating on all elements within the array and find the required id.

Desired Behavior

Create a lens on all elements within the array satisfying the specific predicates, similar to filter.

Example with filter for keys:

const _desiredFilter: Optional<
  UserState,
  ReadonlyArray<Filter>
> = Optic.id<UserState>().at('user').filter(user => user.uuid === 'desiredUUID');

Desired behaviour for index elements.

const _desiredFilter: Optional<
  UserState,
  ReadonlyArray<Filter>
> = Optic.id<UserState>().at('user').at('cats').filter(cat => cat.likesMice);

Suggested Solution

Implement a new method filterIndex similar to filter that returns an Optional.

Who does this impact? Who is this for?

Anyone who uses arrays.

Describe alternatives you've considered

Alternatively a lens factory method may be created, but this is not as clean as it could be.

Your environment

Software Version(s)
@fp-ts/optic 0.10.0
TypeScript 5.1.3

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