|
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) |
|
} |