Skip to content

Instantly share code, notes, and snippets.

@sisi-sh
Created July 3, 2020 01:00
Show Gist options
  • Select an option

  • Save sisi-sh/473e449f332b28d6c2458f1cbc88e59d to your computer and use it in GitHub Desktop.

Select an option

Save sisi-sh/473e449f332b28d6c2458f1cbc88e59d to your computer and use it in GitHub Desktop.
/*
There's two ways to see if the answer matches more efficiently
Both of ways use arrays to contain the answers, and loop through them to find the answer
These are better beacuse
1. they're less lines, and easier to read from a developer's perspective
2. they're also more flexible; say if you wanted to use this code in another app,
or change the words themselves for any other reason, it's easy to edit the answers array
and use the same code again because the actual answers are defined in one place rather
than in each "if" case over and over again
*/
// 1. finding the answer from the array via a for loop
const getUserChoiceLoop = userInput => {
const answers = [
"rock",
"paper",
"scissors"
]
// for loop, if you haven't learned about these you will soon!
for (let i = 0; i < answers.length; i++) {
if (userInput === answers[i]) {
return answers[i];
}
}
/*
the rest of this code will only be reached if the above return was never hit;
meaning nothing in the array matched userInput and therefore we know that userInput
isn't rock, paper, or scissors
*/
// this throws an error to the console
throw("Invalid user input!");
}
// 2. Using Array "higher order functions"
// (this one's a lot more advanced, just wanted to give you a glimpse at this stuff if you were curious)
const getUserChoiceArrayFunction = userInput => {
const answers = [
"rock",
"paper",
"scissors"
]
/*
the "array.filter()" function of an array takes a function as input
it will call the function with each element of the array, and make
a new array containning all elements that caused the function to return true
further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
*/
/*
in this case, it will run thru each element of the answer array,
and any answer that matches the userInput will be added to the matchedAnswers array
*/
let matchedAnswers = answers.filter(answer => userInput === answer)
// ex. if userInput = "paper", matchedAnswers = ["paper"]
// or, if userInput = "potato", matchedAnswers = [] (empty array)
// if one of them matched, the length of the array will be 1
if (matchedAnswers.length === 1) {
return matchedAnswer[0];
}
// if none of them matched, the userInput is invalid, and an error is thrown
else {
throw ("Invalid user input")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment