Update snippets head and last to type check
Update `head` and `last` to check on empty, undefined, null arrays.
This commit is contained in:
@ -5,12 +5,16 @@ tags: array,beginner
|
||||
|
||||
Returns the head of a list.
|
||||
|
||||
Use `arr[0]` to return the first element of the passed array.
|
||||
Check if `arr` is truthy and has a `length` property, use `arr[0]` if possible
|
||||
to return the first element, otherwise return `undefined`
|
||||
|
||||
```js
|
||||
const head = arr => arr[0];
|
||||
const head = arr => (arr && arr.length ? arr[0] : undefined);
|
||||
```
|
||||
|
||||
```js
|
||||
head([1, 2, 3]); // 1
|
||||
```
|
||||
head([]); // undefined
|
||||
head(null); // undefined
|
||||
head(undefined); // undefined
|
||||
```
|
||||
|
||||
@ -5,12 +5,17 @@ tags: array,beginner
|
||||
|
||||
Returns the last element in an array.
|
||||
|
||||
Use `arr.length - 1` to compute the index of the last element of the given array and returning it.
|
||||
Check if `arr` is truthy and has a `length` property, use `arr.length - 1` to
|
||||
compute the index of the last element of the given array and returning it,
|
||||
otherwise return `undefined`
|
||||
|
||||
```js
|
||||
const last = arr => arr[arr.length - 1];
|
||||
const last = arr => (arr && arr.length ? arr[arr.length - 1] : undefined);
|
||||
```
|
||||
|
||||
```js
|
||||
last([1, 2, 3]); // 3
|
||||
```
|
||||
last([]); // undefined
|
||||
last(null); // undefined
|
||||
last(undefined); // undefined
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user