Optimized longestItem

This commit is contained in:
Bruce Feldman
2018-08-12 20:56:24 -04:00
parent 025f4f5534
commit 95e5603702
2 changed files with 3 additions and 3 deletions

View File

@ -2,10 +2,10 @@
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
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

View File

@ -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;