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

Commit aa707bc

Browse files
author
Kevin Hermawan
committed
refactor: improves performance isContainNil in the first and last index
1 parent 3987a0c commit aa707bc

File tree

3 files changed

+30
-16
lines changed

3 files changed

+30
-16
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ console.log(result3); // true
9292
>
9393
> O(n), where n is the length of the array.
9494
>
95-
> O(1), if `index` is the last index of the array.
95+
> O(1), if nil appears in the first or last index.
9696
9797
#### [isEmpty](/src/isEmpty.ts)
9898

src/isContainNil.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
export function isContainNil<T>(array: T[]) {
2-
let result = false;
3-
4-
for (let i = 0; i < array.length; i++) {
5-
if (array[i] === undefined || array[i] === null) {
6-
result = true;
2+
if (
3+
array.length > 0 &&
4+
(array[0] === null ||
5+
array[0] === undefined ||
6+
array[array.length - 1] === null ||
7+
array[array.length - 1] === undefined)
8+
) {
9+
return true;
10+
}
711

8-
break;
9-
}
12+
for (let i = 1; i < array.length - 1; i++) {
13+
if (array[i] === null || array[i] === undefined) return true;
1014
}
1115

12-
return result;
16+
return false;
1317
}

test/isContainNil.test.ts

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,30 @@ import { isContainNil } from '../src/isContainNil';
44

55
describe('isContainNil', () => {
66
it('tests with array that contains `undefined`', () => {
7-
const array = [1, 2, 3, undefined, 5];
7+
const array1 = [undefined, 2, 3, 4, 5];
8+
const array2 = [1, 2, undefined, 4, 5];
9+
const array3 = [1, 2, 3, 4, undefined];
810

9-
const result = isContainNil(array);
10-
expect(result).to.eql(true);
11+
const result1 = isContainNil(array1);
12+
const result2 = isContainNil(array2);
13+
const result3 = isContainNil(array3);
14+
15+
expect([result1, result2, result3]).to.eql([true, true, true]);
1116
});
1217

1318
it('tests with array that contains `undefined`', () => {
14-
const array = [1, 2, 3, null, 5];
19+
const array1 = [null, 2, 3, 4, 5];
20+
const array2 = [1, 2, null, 4, 5];
21+
const array3 = [1, 2, 3, 4, null];
1522

16-
const result = isContainNil(array);
17-
expect(result).to.eql(true);
23+
const result1 = isContainNil(array1);
24+
const result2 = isContainNil(array2);
25+
const result3 = isContainNil(array3);
26+
27+
expect([result1, result2, result3]).to.eql([true, true, true]);
1828
});
1929

20-
it('tests with clean array', () => {
30+
it('tests with clear array', () => {
2131
const array = [1, 2, 3, 4, 5];
2232

2333
const result = isContainNil(array);

0 commit comments

Comments
 (0)