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

The revenge of Array.mapNonEmpty #4240

Open
datner opened this issue Jan 13, 2025 · 1 comment
Open

The revenge of Array.mapNonEmpty #4240

datner opened this issue Jan 13, 2025 · 1 comment
Labels
enhancement New feature or request

Comments

@datner
Copy link
Member

datner commented Jan 13, 2025

What is the problem this feature would solve?

Sometimes I want to use an Array util that requires a NonEmptyArray like Array.group, but the context allows for an empty array. This is obviously solved by Array.match

Array.match({
 onNonEmpty: Array.groupBy(_ => _._tag),
 onEmpty: Array.empty
})

(Yeah yeah tacit usage)

The problem is that this produces a less than ideal type, for the above it'll be never[] | [[Foo, ...Foo[], ....[Foo, ... Foo[]]].
It is not inferable nor can I manually type Array.empty to match since [Foo,...Foo[]][] is not the same as the non-empty tuple type (so you get [Foo,...Foo[]][] | [[Foo, ...Foo[], ....[Foo, ... Foo[]]]).

What is the feature you are proposing to solve the problem?

Since Array.mapNonEmpty has been integrated into Array.map and killed off, I propose to exume its body and reanimating it to do our biddings. That is, allow to map over a non-empty case of an array, removing non-emptiness on the inferred result

declare const foos = Foo[]
Array.mapNonEmpty(foos, Array.groupBy(_ => _._tag)) // [Foo, ...Foo[]][]

This will also solve some recurring issues raised by users who express a desire to work on 0..n sized arrays using 1..n dependant utils, common in cases where validation or input arrives outside of effect , where types are less precise, and the strictness of checking for non-emptiness might feel redundant

Other name suggestions: .applyNonEmpty, .forNonEmpty, .onNonEmpty, or .extendNonEmpty
Though none are stellar lol

What alternatives have you considered?

Array.match<Array.NonEmptyArray<Foo>[], Foo>({
 onNonEmpty: Array.groupBy(_ => _._tag),
 onEmpty: Array.empty
})
@datner datner added the enhancement New feature or request label Jan 13, 2025
@jessekelly881
Copy link
Contributor

It would be quite nice.

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

No branches or pull requests

2 participants