Skip to content

Commit

Permalink
feat(Data-Structures/Array): add function to find last element in an …
Browse files Browse the repository at this point in the history
…array
  • Loading branch information
13jksingh committed Oct 1, 2023
1 parent 964ba04 commit dd33a0a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
17 changes: 17 additions & 0 deletions Data-Structures/Array/FindLastElement.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* (https://www.geeksforgeeks.org/get-the-first-and-last-item-in-an-array-using-javascript/)
* This function will accept an array and
* return the last element of the array.
* If the array is empty, it will return undefined.
* @param {Array} arr array with elements of any data type
* @returns {*} last element of the array
*/
const FindLastElement = (arr) => {
if (arr.length === 0) {
return undefined;
}
return arr[arr.length - 1];
};

export { FindLastElement };

13 changes: 13 additions & 0 deletions Data-Structures/Array/test/FindLastElement.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { FindLastElement } from '../FindLastElement';
import each from 'jest-each';

describe('find last element of an array', () => {
each`
array | expected
${[]} | ${undefined}
${[1]} | ${1}
${[1, 2, 3, 4]} | ${4}
`.test('returns $expected when given $array', ({ array, expected }) => {
expect(FindLastElement(array)).toEqual(expected);
});
});

0 comments on commit dd33a0a

Please sign in to comment.