-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinsert.ts
34 lines (27 loc) · 846 Bytes
/
insert.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
import type { PrototypeStruct } from '../index.js';
interface Insert<T> {
insert(index: number, element: T): void;
}
export const insert: PrototypeStruct = {
label: 'insert',
fn: function arrayInsert<T = unknown>(index: number, element: T): void {
const ctx = this as unknown as T[];
const len = ctx.length;
if (null == index || 'number' !== typeof(index) || index < 0 || index > len) {
throw new TypeError(`Array index out of bound`);
}
if (!index) {
ctx.unshift(element);
} else if (index === len) {
ctx.push(element);
} else {
const startSlice = ctx.slice(0, index);
const endSlice = ctx.slice(index);
ctx.length = 0;
for (const n of startSlice.concat(element, endSlice)) ctx.push(n);
}
},
};
declare global {
interface Array<T> extends Insert<T> {}
}