Skip to content

Commit dd33a0a

Browse files
committed
feat(Data-Structures/Array): add function to find last element in an array
1 parent 964ba04 commit dd33a0a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* (https://www.geeksforgeeks.org/get-the-first-and-last-item-in-an-array-using-javascript/)
3+
* This function will accept an array and
4+
* return the last element of the array.
5+
* If the array is empty, it will return undefined.
6+
* @param {Array} arr array with elements of any data type
7+
* @returns {*} last element of the array
8+
*/
9+
const FindLastElement = (arr) => {
10+
if (arr.length === 0) {
11+
return undefined;
12+
}
13+
return arr[arr.length - 1];
14+
};
15+
16+
export { FindLastElement };
17+
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { FindLastElement } from '../FindLastElement';
2+
import each from 'jest-each';
3+
4+
describe('find last element of an array', () => {
5+
each`
6+
array | expected
7+
${[]} | ${undefined}
8+
${[1]} | ${1}
9+
${[1, 2, 3, 4]} | ${4}
10+
`.test('returns $expected when given $array', ({ array, expected }) => {
11+
expect(FindLastElement(array)).toEqual(expected);
12+
});
13+
});

0 commit comments

Comments
 (0)