jeudi 1 décembre 2016

Is this good practice to structure JavaScript (Functions)?

could an experienced programmer tell if this is good coding practice? I like to my login inside functions and then call them when needed in the main program. Below is a link to a jsfiddle which contains my code.

//Rock, paper and scissors game test
getUserChoice();
var validation = validateUserInput(userChoice);
var computerChoice = computerChoiceGeneration();

console.log(compare(userChoice, computerChoice));


//Functions

function validateUserInput(userInput) {
    if (userInput) {
    if (userInput === "rock" || userInput === "scissors" || userInput === "paper")
        return true;      
    getUserChoice();
  }
  getUserChoice();
}

function computerChoiceGeneration() {
    if (validation) {
    var random = Math.random();
    if (random < 0.34) {
      return "rock";
    } else if (random <= 0.67) {
      return "paper";
    } else {
      return "scissors";
    }
  }
  getUserChoice();
}

function getUserChoice() {
  userChoice = prompt("Please enter rock, paper or scissors?");
  validateUserInput(userChoice);
}

function compare(choice1, choice2) {
  if (choice1 === choice2) {
    return "The result is a tie!";
  }

  if (choice1 === "rock") {
    if (choice2 === "scissors")
      return "rock wins";
    if (choice2 === "paper")
      return "paper wins";
  }

  if (choice1 === "paper") {
    if (choice2 === "rock")
      return "paper wins";
    if (choice2 === "scissors")
      return "scissors wins";
  }

  if (choice1 === "scissors") {
    if (choice2 === "rock")
      return "rock wins";
    if (choice2 === "paper")
      return "scissors wins";
  }
}

http://ift.tt/2gJC7xc

Thank you in advance

Aucun commentaire:

Enregistrer un commentaire