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

Commit 2ad5202

Browse files
author
Kevin Hermawan
committed
refactor: improves performance insertAt
1 parent 683e47e commit 2ad5202

File tree

2 files changed

+7
-11
lines changed

2 files changed

+7
-11
lines changed

README.md

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

6464
> **Time complexity:**
6565
>
66-
> O(n), where n is the length of the array.
66+
> O(n), where n is the remainder of skipped element.
6767
>
6868
> O(1), if `index` is the last index of the array.
6969

src/insertAt.ts

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,19 @@ type InsertAtArgs<T> = {
55

66
export function insertAt<T>(array: T[], args: InsertAtArgs<T>) {
77
const { index, element } = args;
8-
const lastIndex = array.length - 1;
98

10-
if (index === lastIndex || index > lastIndex) {
11-
const result = array;
9+
if (index >= array.length - 1) {
10+
const result = array.slice();
1211
result.push(element);
1312

1413
return result;
1514
}
1615

17-
const result: T[] = [];
16+
const result = array.slice(0, index);
17+
result.push(element);
1818

19-
for (let i = 0; i < array.length; i++) {
20-
if (index === i) {
21-
result.push(element);
22-
}
23-
24-
result.push(array[i]);
19+
for (let i = 0; i < array.length - index; i++) {
20+
result.push(array[index + i]);
2521
}
2622

2723
return result;

0 commit comments

Comments
 (0)