-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy patharraylike-at.ts
40 lines (36 loc) · 1.15 KB
/
arraylike-at.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
const TypedArray = Reflect.getPrototypeOf(Int8Array) as Int8ArrayConstructor | null
export function arrayLikeAt<T>(this: ArrayLike<T>, i: number): T | void {
const l = this.length
i = Math.trunc(i) || 0
if (i < 0) i += l
return i < 0 || i >= l ? undefined : this[i]
}
/*#__PURE__*/
export function isSupported(): boolean {
return (
'at' in Array.prototype &&
typeof Array.prototype.at === 'function' &&
'at' in String.prototype &&
typeof String.prototype.at === 'function' &&
typeof TypedArray === 'function' &&
'at' in TypedArray.prototype &&
typeof TypedArray.prototype.at === 'function'
)
}
/*#__PURE__*/
export function isPolyfilled(): boolean {
return (
Array.prototype.at === arrayLikeAt &&
String.prototype.at === arrayLikeAt &&
typeof TypedArray === 'function' &&
TypedArray.prototype.at === arrayLikeAt
)
}
export function apply(): void {
if (!isSupported()) {
const defn = {value: arrayLikeAt, writable: true, configurable: true}
Object.defineProperty(Array.prototype, 'at', defn)
Object.defineProperty(String.prototype, 'at', defn)
Object.defineProperty(TypedArray, 'at', defn)
}
}