-
Notifications
You must be signed in to change notification settings - Fork 15
feat(@angular-ru/common): support nullable for array utils #682
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
Conversation
@@ -0,0 +1,5 @@ | |||
import { Nullable } from '@angular-ru/common/typings'; | |||
|
|||
export function takeFirstItem<T>(array?: Nullable<T[]>): Nullable<T> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Generates tuples with given length. [type]
and [type, ...type[]]
.
type Tuple<T, N extends number = 1, R extends unknown[] = []> = R['length'] extends N ? R : Tuple<T, N, [T, ...R]>;
type InfiniteTuple<T, N extends number = 1> = [...Tuple<T, N>, ...T[]];
Returns type of Index
s item of array or fallbacks to undefined
. if there is no certainty that the element is presented, append undefined
.
type ItemOrUndefined<ArrayType, Index extends number> = ArrayType extends unknown[]
? ArrayType extends [unknown, ...InfiniteTuple<unknown, Index>]
? ArrayType[0]
: ArrayType[0] | undefined
: undefined;
Now let's use it in our function return type:
export function takeFirstItem<ArrayType extends Nullable<unknown[]>>(array: ArrayType): ItemOrUndefined<ArrayType, 0> {
return (Array.isArray(array) ? array[0] : undefined) as ItemOrUndefined<ArrayType, 0>;
}
And another functions:
export function takeSecondItem<ArrayType extends Nullable<unknown[]>>(array: ArrayType): ItemOrUndefined<ArrayType, 1> {
return (Array.isArray(array) ? array[1] : undefined) as ItemOrUndefined<ArrayType, 1>;
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
* feat(@angular-ru/common): support nullable values when update array * feat(@angular-ru/common): support nullable for array utils
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
Issue Number: N/A
What is the new behavior?
Does this PR introduce a breaking change?
Other information