-
-
Notifications
You must be signed in to change notification settings - Fork 654
Add ArrayReverse type
#1266
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
base: main
Are you sure you want to change the base?
Add ArrayReverse type
#1266
Conversation
This comment was marked as resolved.
This comment was marked as resolved.
0e9cfea to
af7ed2a
Compare
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
|
For inputs containing only optional elements, I originally wasn't splitting the result, for example, |
|
@benzaria Would appreciate if you could share your thoughts on this! |
Co-authored-by: benz <[email protected]>
7e59b1b to
5aaf11d
Compare
This comment was marked as outdated.
This comment was marked as outdated.
|
@sindresorhus While adding test for long tuples, I realised my implementation was not tail recursive because I had simplified a conditional using the So, does it make sense to add a note like the following to the Note: Sometimes using the import type {If, IsEqual, StringRepeat} from 'type-fest';
// The following implementation is not tail recursive
type Includes<S extends string, Char extends string> =
S extends `${infer First}${infer Rest}`
? If<IsEqual<First, Char>,
'found',
Includes<Rest, Char>>
: 'not found';
// Hence, instantiations with long strings will fail
type HundredZeroes = StringRepeat<'0', 100>;
// @ts-expect-error
type Fails = Includes<HundredZeroes, '1'>;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Error: Type instantiation is excessively deep and possibly infinite.
// However, if we use a simple conditional instead of `If`, the implementation becomes tail-recursive
type IncludesWithoutIf<S extends string, Char extends string> =
S extends `${infer First}${infer Rest}`
? IsEqual<First, Char> extends true
? 'found'
: IncludesWithoutIf<Rest, Char>
: 'not found';
// Now, instantiations with long strings will work
type Works = IncludesWithoutIf<HundredZeroes, '1'>;
//=> 'not found' |
Definitely makes sense 👍 |
This PR fixes this issue in #1167. I was playing around with the fix and had done most of the work in the process, so I thought I’d open a separate PR.
Credits to @benzaria for suggesting this type.
Reverseworks normally when the input array doesn't contain optional elements, but if the array includes an optional element, the result splits into a union of separate tuples, like:type-fest/source/array-reverse.d.ts
Lines 30 to 50 in 1c2e057
I've kept the name as
ArrayReverseinstead of justReverseto match with our existingArray*types (likeArraySlice,ArraySplice).