Home > Net >  How to repeat part of a switch statement without duplicating code / alternatives
How to repeat part of a switch statement without duplicating code / alternatives

Time:12-09

I am creating a random sentence generator. The sentence generated will hold values that have been randomly selected from an objects properties. properties are; nouns, tenses, adjectives conjunctions.

The sentence will be in the order of "noun tense adjective conjunction noun tense adjective" Example output = "Birds will be wild and robots will be free"

I have created this using for in loop switch statements, however I have repeated code in order to do so. I'm wondering is there is a more efficient way to do this?

Code:

// Generating a random number
function generateRandomNumber(num) {
  return Math.floor(Math.random() * num)
}

// The object containing the properties and values, the values will be the words in the sentence.
const sentenceElements = {
  nouns: [ 'animals', 'elephants', 'mice', 'monkeys', 'lions', 'zebras', 'people', 'buildings', 'trees', 'flowers', 'bugs', 'cats', 'birds', 'mushrooms', 'computers', 'robots', 'dinosaurs' ],
  tenses: [ 'were', 'are', 'will be',  ],
  adjectives: [ 'best', 'bad', 'better', 'huge', 'busy', 'free', 'great', 'hard', 'loud', 'old', 'right', 'special', 'weird', 'brave', 'wild', 'adorable', 'smart', 'crazy', 'cute', 'funny' ],
  conjunctions: [ 'because', 'however', 'since', 'but', 'whereas', 'and', 'also', 'as', 'when' ]
}

// Empty array for the selected words to be pushed into
let newArray = []

// Looping through the properties in the object to push each randomly selected value into the empty array.
for(let i in sentenceElements) {
  let randArrayIndex = generateRandomNumber(sentenceElements[i].length)

  switch(i) {
    case 'nouns':
      newArray.push(`${sentenceElements[i][randArrayIndex]}`)
      break
    case 'tenses':
      newArray.push(`${sentenceElements[i][randArrayIndex]}`)
      break
    case 'adjectives':
      newArray.push(`${sentenceElements[i][randArrayIndex]}`)
      break
    case 'conjunctions':
      newArray.push(`${sentenceElements[i][randArrayIndex]}`)
      break
  }
}
// Used another for in loop to add more words to the array using the same object.
for(let i in sentenceElements) {
  let randArrayIndex = generateRandomNumber(sentenceElements[i].length)

  switch(i) {
    case 'nouns':
      newArray.push(`${sentenceElements[i][randArrayIndex]}`)
      break
    case 'tenses':
      newArray.push(`${sentenceElements[i][randArrayIndex]}`)
      break
    case 'adjectives':
      newArray.push(`${sentenceElements[i][randArrayIndex]}`)
      break
  }
} 
// Adding the values from newArray to a string called completeSentence while capitalizing the first letter
function completeSentence(sentence) {
  const formatting = newArray.join(' ') 
  const formatted = formatting[0].toUpperCase()   formatting.substring(1)
  console.log(formatted)
}

completeSentence(newArray); 

Thanks

CodePudding user response:

Your code is tightly coupling the order of the sentenceElements object's keys to the structure of the sentence. This makes it needlessly inflexible.

Instead, you can create a function that generates a random sentence element of a given type:

function randomSentenceElement(type) {
    const elements = sentenceElements[type]
    return elements[generateRandomNumber(elements.length)]
}

Then you can easily compose sentences in any order you wish, with much less code:

let newArray = ['nouns', 'tenses', 'adjectives', 'conjunctions', 'nouns', 'tenses', 'adjectives']
    .map(randomSentenceElement)

CodePudding user response:

In a simple form, if you just want to remove the duplicated switch you could add a while loop, around your switch and another int variable, which will loop for 'x' number of sentences you want to generate. The below should loop 2 times for you.

let newArray = []
let sentencesToGenerate = 2;

while (newArray.length < sentencesToGenerate)
{
    // Looping through the properties in the object to push each randomly selected value into the empty array.
    for(let i in sentenceElements) {
      let randArrayIndex = generateRandomNumber(sentenceElements[i].length)

      switch(i) {
        case 'nouns':
          newArray.push(`${sentenceElements[i][randArrayIndex]}`)
          break
        case 'tenses':
          newArray.push(`${sentenceElements[i][randArrayIndex]}`)
          break
        case 'adjectives':
          newArray.push(`${sentenceElements[i][randArrayIndex]}`)
          break
        case 'conjunctions':
          newArray.push(`${sentenceElements[i][randArrayIndex]}`)
          break
      }
    }
    sentencesToGenerate  ;
}
  • Related