Home > Blockchain >  How to flip and/or count backwards [closed]
How to flip and/or count backwards [closed]

Time:09-28

Hey guys im developing something and I need to fix this please give me some feedback on how to improve this. (how to make it cleaner, easier to read , etc). Here's the code!

function wordFliper(word) {
    let wordOutput = "";
    let reverseIndex = word.length - 1;
    for (let index = reverseIndex; index >= 0; index--) {
      let storage = word[index];
      wordOutput = wordOutput   storage;
    }
    return wordOutput;
  }

CodePudding user response:

You can use JS array functions like reduce(),split(),reverse(), etc. You can write the code in following ways:

  1. function wordFlipper(word) {
        return(word.split('').reverse().join(''));
    }
    
  2. function wordFlipper(word) {
        return(word.split('').reduce((a,c)=>c a));
    }
    

Please go through the links for clarity on the functions used above:

CodePudding user response:

I would remove some variables (variables that are used once in loop and then assigned to a function variable) to reduce code and rename one like this:

/// <summary>Function to flip words backwards</summary>
/// <param name="word" type="string">Word to be flipped</param>
/// <returns type="string">Word flipped</returns>

function wordFlipper(word) {
    let flippedWord = "";
    for (let i = word.length - 1; i >= 0; i--) {
      flippedWord  = word[i];
    }
    return flippedWord;
}

Also IMHO use i variable instead of index (for loop incrementer)

And Also get used to commenting your code, to know what is for the functions you're writing

I hope you helped to keep your code clean for further programming and happy coding!

  • Related