Added support for arrays and single strings

This commit is contained in:
Enzo Volkmann
2018-01-08 08:22:04 +01:00
parent 02bdb13193
commit d82dbb7ff8

View File

@ -1,16 +1,26 @@
### longestString ### longestString
Takes an array of strings and returns the longest one. 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) 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. to handle arrays as well as an indefinite amount of single arguments.
Strings are compared using `Array.reduce()`. Strings are compared using `Array.reduce()`.
```js ```js
const longestString = (...strings) => [...strings].reduce((a, b) => a.length > b.length ? a : b); 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 ```js
longestString('this', 'is', 'a', 'testcase') // 'testcase' longestString('this', 'is', 'a', 'testcase'); // 'testcase'
longestString(['a', 'ab', 'abc']) // 'abc' longestString(['a', 'ab', 'abc']); // 'abc'
longestString(['a', 'ab', 'abc'], 'abcd'); // 'abcd'
``` ```