DEV Community


Discussion on: Keeping Your Code Simple

jhotterbeekx profile image
John Hotterbeekx • Edited

Cleaning code while using lambda expressions can be challenging with times. How I usually try to clean it, is by extracting the actual expression to a separate function, since this usually has its own responsibility.

I'd refactor it like this:

function getLongestStringInArray(stringArray) {
  return stringArray.reduce((str1, str2) => getLongestString(str1, str2));

function getLongestString(string1, string2) {
  if (string2.length > string1.length) return string2;
  return string1;

By splitting the functionality and also removing the inline if statements and arrowbody functions it becomes a lot more readable in my opinion. It also becomes a lot more testable, since you can easily write you test cases for getLongestString testing all comparison options, and afterwards testing array specific behavior only for getLongestStringInArray.