-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(Data-Structures/Array): add function to find last element in an …
…array
- Loading branch information
Showing
2 changed files
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |