Skip to content

Commit 19cab94

Browse files
committed
Splice
1 parent bdd80a1 commit 19cab94

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

src/lualib/ArraySplice.ts

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
// https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
2+
function __TS__ArraySplice<T>(list: T[], start: number, deleteCount: number, ...items: T[]) {
3+
// 1. 2.
4+
const len = list.length;
5+
6+
let actualStart;
7+
8+
// 4.
9+
if (start < 0) {
10+
actualStart = Math.max(len + start, 0);
11+
} else {
12+
actualStart = Math.min(start, len);
13+
}
14+
15+
// 13.
16+
// 14.
17+
const itemCount = items.length;
18+
19+
// 5. - 7.
20+
let actualDeleteCount: number;
21+
22+
if (!start) {
23+
actualDeleteCount = 0;
24+
} else if (!deleteCount) {
25+
actualDeleteCount = len - actualStart;
26+
} else {
27+
actualDeleteCount = Math.min(Math.max(deleteCount, 0), len - actualStart);
28+
}
29+
30+
// 8. ignored
31+
32+
// 9.
33+
const out: T[] = [];
34+
35+
// 10.
36+
let k = 0;
37+
38+
// 11.
39+
for (k = 0; k < actualDeleteCount; k++) {
40+
const from = actualStart + k;
41+
42+
if (list[from]) {
43+
out[k] = list[from];
44+
}
45+
}
46+
47+
// 15.
48+
if (itemCount < actualDeleteCount) {
49+
// a. b.
50+
for (k = actualStart; k < len - actualDeleteCount; k++) {
51+
const from = k + actualDeleteCount;
52+
const to = k + itemCount;
53+
54+
if (list[from]) {
55+
list[to] = list[from];
56+
} else {
57+
list[to] = undefined;
58+
}
59+
}
60+
// c. d.
61+
for (k = len; k > len - actualDeleteCount + itemCount; k--) {
62+
list[k] = undefined;
63+
}
64+
// 16.
65+
} else if (itemCount > actualDeleteCount) {
66+
67+
for (k = len - actualDeleteCount; k > actualStart; k--) {
68+
const from = k + actualDeleteCount - 1;
69+
const to = k + itemCount - 1;
70+
71+
if (list[from]) {
72+
list[to] = list[from];
73+
} else {
74+
list[to] = undefined;
75+
}
76+
77+
}
78+
}
79+
80+
// 17.
81+
// 18.
82+
for (k = actualStart; k < items.length; k++) {
83+
const e = items[k];
84+
list[k] = e;
85+
}
86+
87+
// 19.
88+
for (k = list.length; k > len - actualDeleteCount + itemCount; k--) {
89+
list[k] = undefined;
90+
}
91+
92+
// 20.
93+
return out;
94+
}

0 commit comments

Comments
 (0)