cachaito
10/29/2015 - 1:48 PM

Refactoring tips

//lame
function getName(firstName, lastName) {
  if (firstName && lastName) {
    return firstName + ' ' + lastName;
  } else if (firstName) {
    return firstName;
  } else if (lastName) {
    return lastName;
  } else if (!firstName && !lastName) {
    return 'stranger';
  }
}

//nice
function getName(firstName, lastName) {
  let name = '';
  if (firstName) {
    name = firstName;
  }
  if (lastName) {
    name += ' ' + lastName;
  }
  return getNameOrFallback(name.trim(), 'stranger');
}

function getNameOrFallback(name, fallback) {
  return name || fallback;
}