Skip to content

Instantly share code, notes, and snippets.

@LongLiveCHIEF
Last active October 17, 2017 02:33
Show Gist options
  • Save LongLiveCHIEF/5e16a2fc9a5f6ea97231c52864ee0fa2 to your computer and use it in GitHub Desktop.
Save LongLiveCHIEF/5e16a2fc9a5f6ea97231c52864ee0fa2 to your computer and use it in GitHub Desktop.
Rock, Paper, Scissors (Lizard, Spock, Enterprise, Klingon) for Node.js

Follow the docs in rps.js, or if you want to run with docker, save both rps.js and Dockerfile in the same directory, run:

$ docker build -t rps .
$ docker run -it --rm rps rock scissors
When rock faces scissors, rock wins!
FROM node:latest
RUN mkdir /rps
COPY rps.js /rps/rps.js
ENTRYPOINT ["node", "/rps/rps.js"]
const rpsThrows = process.argv.slice(2);
const matrix = {
rock: {
beats: ['scissors','lizard', 'enterprise']
},
paper: {
beats: ['rock', 'spock', 'klingon']
},
scissors: {
beats: ['paper', 'lizard', 'scissors']
},
lizard: {
beats: ['paper', 'spock', 'scissors']
},
spock: {
beats: ['rock','klingon', 'enterprise']
},
enterprise: {
beats: ['paper', 'scissors', 'lizard']
},
klingon: {
beats: ['lizard', 'scissors', 'rock']
}
}
processRpsThrows();
/* Private functions for processing RPS Matches */
function processRpsThrows(matrix, rpsThrows){
// make sure all throws are valid
validateRpsMatch()
// determine winner
var rpsMatchWinner = determineRpsMatchWinner();
// display results
displayRpsMatchResults(rpsMatchWinner);
}
// ensures RPS Matchthrows are valid
function validateRpsMatch(){
rpsThrows.forEach(arg => ensureRpsThrowIsValid(arg))
if (rpsThrows.length != 2){
exitRpsMatchWithError('ERROR: Exactly 2 throws must be provided')
}
if (rpsThrows[0] === rpsThrows[1]){
exitRpsMatchWithError('NO WINNER, both throws are the same')
}
}
// ensure a given thrown is valid
function ensureRpsThrowIsValid(arg){
if (matrix[arg] === undefined) {
exitRpsMatchWithError(`ERROR: ${arg} is not a valid throw`);
}
}
// determine the winner of the match
function determineRpsMatchWinner(){
//if (matrix[rpsThrows[0]]['beats'] == rpsThrows[1])
if (matrix[rpsThrows[0]]['beats'].indexOf(rpsThrows[1]) > -1 ){
return rpsThrows[0]
} else {
return rpsThrows[1]
}
}
function displayRpsMatchResults(winner){
console.log(`When ${rpsThrows[0]} faces ${rpsThrows[1]}, ${winner} wins!`)
}
function exitRpsMatchWithError(message){
console.error(message)
process.exit(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment