Optimized longestItem
This commit is contained in:
@ -2,10 +2,10 @@
|
|||||||
|
|
||||||
Takes any number of iterable objects or objects with a `length` property and returns the longest one.
|
Takes any number of iterable objects or objects with a `length` property and returns the longest one.
|
||||||
|
|
||||||
Use `Array.sort()` to sort all arguments by `length`, return the first (longest) one.
|
Use `Array.reduce()` to collect the longest element. Returns [] for empty array.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0];
|
const longestItem = (...vals) => [...vals].reduce((a, x) => (a.length > x.length ? a : x), []);
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -1,2 +1,2 @@
|
|||||||
const longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0];
|
const longestItem = (...vals) => [...vals].reduce((a, x) => (a.length > x.length ? a : x), []);
|
||||||
module.exports = longestItem;
|
module.exports = longestItem;
|
||||||
|
|||||||
Reference in New Issue
Block a user