Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make this JS repetitive code shorter

I just wrote this piece of code that does the thing it’s supposed to do, although it’s really messy and pretty repetitive and I’m wondering how can I make it much shorter and concise.

if(id==1 && player == "playerOne"){
      Object.assign(playerOne, fighters[0])
    }else if(id==1 && player =="playerTwo"){
      Object.assign(playerTwo, fighters[0])
    }
    if(id==2 && player == "playerOne"){
      Object.assign(playerOne, fighters[1])
    }else if(id==2 && player =="playerTwo"){
      Object.assign(playerTwo, fighters[1])
    }
    if(id==3 && player == "playerOne"){
      Object.assign(playerOne, fighters[2])
    }else if(id==3 && player =="playerTwo"){
      Object.assign(playerTwo, fighters[2])
    }
    if(id==4 && player == "playerOne"){
      Object.assign(playerOne, fighters[3])
    }else if(id==4 && player =="playerTwo"){
      Object.assign(playerTwo, fighters[3])
    }
    if(id==5 && player == "playerOne"){
      Object.assign(playerOne, fighters[4])
    }else if(id==5 && player =="playerTwo"){
      Object.assign(playerTwo, fighters[4])
    }
    if(id==6 && player == "playerOne"){
      Object.assign(playerOne, fighters[5])
    }else if(id==6 && player =="playerTwo"){
      Object.assign(playerTwo, fighters[5])
    }
    if(id==7 && player == "playerOne"){
      Object.assign(playerOne, fighters[6])
    }else if(id==7 && player =="playerTwo"){
      Object.assign(playerTwo, fighters[6])
    }
    if(id==8 && player == "playerOne"){
      Object.assign(playerOne, fighters[7])
    }else if(id==8 && player =="playerTwo"){
      Object.assign(playerTwo, fighters[7])
    }
    if(id==9 && player == "playerOne"){
      Object.assign(playerOne, fighters[8])
    }else if(id==9 && player =="playerTwo"){
      Object.assign(playerTwo, fighters[8])
    }

Thank you in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming

a) there are no more than two players

b) you don’t care that this code handles id < 1 and id > 9

It looks to me like you could reduce this to a single line.

Object.assign(player == "playerOne" ? playerOne : playerTwo, fighters[id - 1])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading