Based on suggestions, added longestItem()

This commit is contained in:
Enzo Volkmann
2018-01-08 20:33:47 +01:00
parent 69393c1c7f
commit d080d1f3dd
2 changed files with 17 additions and 26 deletions

17
snippets/longestItem.md Normal file
View File

@ -0,0 +1,17 @@
### longestItem
Takes any iterable object or object with a `length` property and returns the longest one.
The function sorts all arguments by their `length` and returns the first (longest) one.
```js
const longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0];
```
```js
longestItem ('this', 'is', 'a', 'testcase'); // 'testcase'
longestItem (...['a', 'ab', 'abc']); // 'abc'
longestItem (...['a', 'ab', 'abc'], 'abcd'); // 'abcd'
longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
longestItem([1, 2, 3], 'foobar'); // 'foobar'
```

View File

@ -1,26 +0,0 @@
### longestString
Takes an array of strings and returns the longest one.
The method also accepts combinations of single strings and string arrays
Uses the [rest operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)
to handle arrays as well as an indefinite amount of single arguments.
Strings are compared using `Array.reduce()`.
```js
const longestString = (...strings) => strings.map(str => {
if (Array.isArray(str)) {
const first = str.shift();
strings.concat(str);
return first;
} else {
return str;
}
}).reduce((a, b) => a.length > b.length ? a : b);
```
```js
longestString('this', 'is', 'a', 'testcase'); // 'testcase'
longestString(['a', 'ab', 'abc']); // 'abc'
longestString(['a', 'ab', 'abc'], 'abcd'); // 'abcd'
```