diff --git a/snippets/longestItem.md b/snippets/longestItem.md new file mode 100644 index 000000000..31afe5bb9 --- /dev/null +++ b/snippets/longestItem.md @@ -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' +``` diff --git a/snippets/longestString.md b/snippets/longestString.md deleted file mode 100644 index a7feb3c3d..000000000 --- a/snippets/longestString.md +++ /dev/null @@ -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' -```