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

Commit 271ec14

Browse files
author
Kevin Hermawan
committed
fix: push a new element to the last when the index is out of range
1 parent 7d43612 commit 271ec14

File tree

2 files changed

+16
-20
lines changed

2 files changed

+16
-20
lines changed

src/insertAt.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,7 @@ export function insertAt<T>(array: T[], args: InsertAtArgs<T>) {
77
const { index, element } = args;
88
const lastIndex = array.length - 1;
99

10-
if (index > lastIndex) {
11-
return array;
12-
}
13-
14-
if (index === lastIndex) {
10+
if (index === lastIndex || index > lastIndex) {
1511
const result = array;
1612
result.push(element);
1713

test/insertAt.test.ts

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,24 +10,24 @@ describe('insertAt', () => {
1010
expect(result).to.eql([9, 1, 2, 3, 4, 5]);
1111
});
1212

13-
// it('inserts element into the middle', () => {
14-
// const array = [1, 2, 3, 4, 5];
13+
it('inserts element into the middle', () => {
14+
const array = [1, 2, 3, 4, 5];
1515

16-
// const result = insertAt(array, { index: 3, element: 9 });
17-
// expect(result).to.eql([1, 2, 3, 9, 4, 5]);
18-
// });
16+
const result = insertAt(array, { index: 3, element: 9 });
17+
expect(result).to.eql([1, 2, 3, 9, 4, 5]);
18+
});
1919

20-
// it('inserts element into the last', () => {
21-
// const array = [1, 2, 3, 4, 5];
20+
it('inserts element into the last', () => {
21+
const array = [1, 2, 3, 4, 5];
2222

23-
// const result = insertAt(array, { index: array.length - 1, element: 9 });
24-
// expect(result).to.eql([1, 2, 3, 4, 5, 9]);
25-
// });
23+
const result = insertAt(array, { index: array.length - 1, element: 9 });
24+
expect(result).to.eql([1, 2, 3, 4, 5, 9]);
25+
});
2626

27-
// it('handles index out of range', () => {
28-
// const array = [1, 2, 3, 4, 5];
27+
it('handles index out of range', () => {
28+
const array = [1, 2, 3, 4, 5];
2929

30-
// const result = insertAt(array, { index: 99, element: 9 });
31-
// expect(result).to.eql([1, 2, 3, 4, 5, 9]);
32-
// });
30+
const result = insertAt(array, { index: 99, element: 9 });
31+
expect(result).to.eql([1, 2, 3, 4, 5, 9]);
32+
});
3333
});

0 commit comments

Comments
 (0)