More efficient choice comparison for Rock Paper Scissors

前端 未结 6 908
你的背包
你的背包 2021-01-07 23:54

This is an ongoing school project that I would like to improve. The point is to make the code as efficient (or short) as possible. I would like to reduce it by finding an al

6条回答
  •  自闭症患者
    2021-01-08 00:39

    Since more strightforward answers were already provided, I wrote you an alternative using more advance features of javascript. These features are an overkill for the problem at hand, but are useful as a learning exercise.

    // Create an array 'battle' as a result from mapping over the given options
    
    const battle = ["Rock", "Paper", "Scissors"].map(
    /* The resulting array is conformed of tuples (arrays of 2 values).
     The first value is the weapon of choice and the second value is a function.
     That function will receive as an argument another weapon and will return the outcome of battling the first option with the second.
     Positive number is win, 0 is tie and negative number is loose. */
      (weapon, index, array) => [weapon, enemy => {
        const res = index - array.findIndex(x => x === enemy)
        return !!(res%2)? res : res * -1
      }]
    /* The reduce transform the array of tuples into an object,
     with each choice as a property key and each function as the property value */
    ).reduce((accumulator, current) => {accumulator[current[0]] = current[1]; return accumulator}, {})
    
    /* Output is just a function that receives your weapon.
      It returns a function that receives your enemy's weapon.
      Which in turn uses the previous object with functions to get the result.
      Finally it uses the result to print one sentence or other, using template strings. */
    
    const output = mine => enemy => {
      const result = battle[mine](enemy)
      return result > 0 ? `You won! ${mine} beats ${enemy}`
      : result < 0 ? `You lost! ${enemy} beats ${mine}`
        : "It's a tie! Try again to win"
    }
    
    console.log(output("Rock")("Paper"))
    

提交回复
热议问题