-
Notifications
You must be signed in to change notification settings - Fork 0
/
includes.ts
118 lines (85 loc) · 2.66 KB
/
includes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { includes } from "lodash"
import { Decrement, Increment, IsNegative, Abs, IsStringRecord, IfAny, IsAny, ConvertNegativeIndex } from "../utils"
const a = includes([1, 2, 3], 1);
// a = true
const b = includes([1, 2, 3], 1, 2);
// b = false
const c = includes({ 'a': 1, 'b': 2 }, 1);
// c = true
const d = includes('abcd', 'bc');
// d = true
// ------------------------------------------------------------------------------------------------------------------
type IncludesArray<T extends readonly any[], V, S extends number = 0, I extends number = 0> = T["length"] extends 0
? false
: T extends readonly [infer L, ...infer Rest]
? I extends S
? L extends V
? true
: IncludesArray<Rest, V, S, I>
: IncludesArray<Rest, V, S, Increment<I>>
: boolean
type IncludesObject<T, V> = V extends T[keyof T] ? true : false
type IncludesString<T extends string, V extends string, S extends number = 0, I extends number = 0> = T extends `${string}${infer Rest}`
? Rest extends ""
? false
: I extends S
? T extends `${string}${V}${string}` ? true : false
: IncludesString<Rest, V, S, Increment<I>>
: boolean
type Includes<T extends Record<string, any> | any[] | string, V, S extends number = 0> =
IsAny<V> extends true ? boolean :
T extends readonly any[]
? IncludesArray<
T,
V,
ConvertNegativeIndex<T, S>
>
: T extends string
? IncludesString<
T,
V & string,
ConvertNegativeIndex<T, S>
>
: true extends IsStringRecord<T> | IsStringRecord<V> ? boolean : IncludesObject<T, V>
type T0 = Includes<[1, 2, 3], 1>
// ^?
type T1 = Includes<[2, 1, 3], 1, 2>
// ^?
type T2 = Includes<[2, 1, 1], 1, 2>
// ^?
type T3 = Includes<{ 'a': 1, 'b': 2 }, 1>
// ^?
type T4 = Includes<{ 'a': 1, 'b': 2 }, 3>
// ^?
type T5 = Includes<'abcd', 'bc'>
// ^?
type T6 = Includes<'abcd', 'bc', 2>
// ^?
type T7 = Includes<'abcd', 'bc', 1>
// ^?
type T8 = Includes<[1, 2, 3, 4], 2, -2>
// ^?
type T9 = Includes<[1, 2, 3, 4], 2, -3>
// ^?
type T10 = Includes<'abcd', 'bc', -2>
// ^?
type T11 = Includes<'abcd', 'bc', -3>
// ^?
type T12 = Includes<number[], number[], -3>
// ^?
type T13 = Includes<string, string>
// ^?
type T14 = Includes<Record<string, any>, Record<string, any>>
// ^?
type T15 = Includes<any, any>
// ^?
type T16 = Includes<string, any>
// ^?
type T17 = Includes<'abcd', any>
// ^?
type T18 = Includes<{ 'a': 1, 'b': 2 }, Record<string, any>>
// ^?
type T19 = Includes<readonly [1, 2, 3, 4], 2, 1>
// ^?
type T20 = Includes<readonly [1, 2, 3, 4], 2, 3>
// ^?