Search code examples
javascriptreactjslodash

Data formula to work out 3 scenarios from one value


Please help! :) Here is my data:

state = {
        data: [
            createData('23 May 2017', 'Seniors', 'Brazil', '90 mins', '3:0'),
            createData('14 May 2017', 'Seniors', 'Italy', '45 mins', '0:0'),
            createData('14 Nov 2016', 'Seniors', 'Germany', '0 mins', '0:2')
        ],
    };`

The value I am interested in is the score e.g '3:0' this would be a home win so I need a formula to give the result 'won' see the 3 scenarios below:

if first value > second = won

if first value = second = drew

if first value < second = loss

I then use the result of won, lost or drew to feed my const

const statusStyle = result.includes("Won") ? "text-white bg-success" : result.includes("Drew") ? "bg-amber" : result.includes("Lost") ? "text-white bg-danger" : "text-white bg-grey";

I have _lodash if this can be used to get turn the data?


Solution

  • Split the score (3:0 for example) by the : sign, and destructure to two consts, then compare the consts:

    const getGameResult = (score) => {
      const [a, b] = score.split(':');
      
      if(a > b) return 'won';
      
      if(a < b) return 'lost';
      
      return 'draw';
    }
    
    console.log(getGameResult('3:0')); // won
    console.log(getGameResult('0:0')); // draw
    console.log(getGameResult('0:2')); // lost