-1

How can I clean my code up to not use functions inside functions?

function toRodCase(input) {
    if(!input) {
        return '';
    }

    function capitalizeFirstLetter(string) {
      return string.charAt(0).toUpperCase() + string.slice(1);
    }
    
    function lowerCaseFirstLetter(string) {
        return string.charAt(0).toLowerCase() + string.slice(1);
    }
        
    let words = input.split(' ');
    for(let i = 0; i < words.length; i++){
        if(i === 0){
            words[i] = lowerCaseFirstLetter(words[i]);
        }else{
            words[i] = 'ROD' + capitalizeFirstLetter(words[i]);
        }
    }
    
    return words.join('');
}
 toRodCase("Hello there stealth warrior")

Right now I have two functions within a function. How can I reduce this or is there a better way to do this?

andy86
  • 75
  • 1
  • 6
  • Since they're only used once and are only a single expression… just not make them functions at all? – deceze Nov 04 '20 at 13:54

1 Answers1

1

Consider using regular expressions. Building on @christian-c-salvadó 's answer to a very similar use case here: Converting any string into camel case, you could shorten your function to the following:

function toRodCase(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index === 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, 'ROD');
}

This utilises a regular expression to first make the necessary uppercase / lowercase changes, and then replaces each space with your chosen spacer.

You could genercise this to use any separator as follows:

function toSpacedCase(str, spacer) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index === 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, spacer);
}