Skip to content
This repository was archived by the owner on Jan 12, 2023. It is now read-only.

Commit f6b6a94

Browse files
author
Kevin Hermawan
committed
refactor: improves performance removeAt
1 parent 2ad5202 commit f6b6a94

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ console.log(result); // [1, 2, 3, 5]
129129

130130
> **Time complexity:**
131131
>
132-
> O(n), where n is the length of the array.
132+
> O(n), where n is the remainder of skipped element.
133133
>
134134
> O(1), if `index` is the last index of the array.
135135

src/removeAt.ts

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,24 @@ type RemoveAtArgs = {
44

55
export function removeAt<T>(array: T[], args: RemoveAtArgs) {
66
const { index } = args;
7-
const lastIndex = array.length - 1;
87

9-
if (index > lastIndex) {
10-
return array;
8+
if (index === array.length - 1) {
9+
const result = array.slice();
10+
result.pop();
11+
12+
return result;
1113
}
1214

13-
const result: T[] = [];
15+
if (index < array.length - 1) {
16+
const result = array.slice(0, index + 1);
17+
result.pop();
1418

15-
for (let i = 0; i < array.length; i++) {
16-
if (index !== i) {
17-
result.push(array[i]);
19+
for (let i = 1; i < array.length - index; i++) {
20+
result.push(array[index + i]);
1821
}
22+
23+
return result;
1924
}
2025

21-
return result;
26+
return array;
2227
}

0 commit comments

Comments
 (0)