DEV Community

Discussion on: Keeping Your Code Simple

Collapse
 
lexlohr profile image
Alex Lohr

Sometimes, there's an even simpler solution:

const strs = ['hello', 'goodbye', 'farewell', 'aloha'];

strs.sort((str1, str2) => str2.length - str2.length);

const longestString = strs[0];
Collapse
 
fc250152 profile image
Nando

I don't think this is a simpler solution, albeit from a logical point of view: it may be understood only considering the outcome of the sorting process, then getting the first item as the one with the minor size...

Collapse
 
layzee profile image
Lars Gyrup Brink Nielsen • Edited

If you turn that into a reusable function, you will be mutating the array parameter, i.e. sorting it in-place. You would have to clone the array before sorting it to prevent side effects from passing an array into the function.

Also, you made a mistake. You compare str2.length to str2.length (both are str2).

Use this instead

function longest(xs) {
  // Shallow clone
  xs = [...xs];
  xs.sort((a, b) => b.length - a.length);

  return xs[0];
}

Or with reusable functions

function compareLength(a, b) {
  return b.length - a.length;
}

function head([first, ...rest]) {
  return first;
}

function longest(xs) {
  xs = shallowClone(xs);
  xs.sort(compareLength);

  return head(xs);
}

function shallowClone(xs) {
  return [...xs];
}
Collapse
 
lexlohr profile image
Alex Lohr

You're right.

Collapse
 
themightyt_v3 profile image
theMightiestT

i thought the same... and if you have strings with numbers, then add a return (a-b) or something...

Collapse
 
buinauskas profile image
Evaldas Buinauskas

Seems that sort has worse performance compared to reduce. Reduce is O(n) while sort is O(n long)

Thread Thread
 
lexlohr profile image
Alex Lohr

Yes, the performance is worse. But unless you need the solution to scale to arrays with more than a few thousand words, this will hardly be an issue.

Thread Thread
 
buinauskas profile image
Evaldas Buinauskas

True. Just wrote that because it wasn't mentioned anywhere and someone might care about it.

Thread Thread
 
themightyt_v3 profile image
theMightiestT

valid point but I agree with Alex... not sure it would really be a thing in an implementation like this