javascript - How do you refactor a big chunk of conditionals? -
i'm making game player can click action button. action button different things depending on context.
function doaction() { if (standingonitem) { if (itemonground === potion) { if (equippieditem === potion) { // mix potions return; } if (equippieditem === torch) { // boil potion return; } // pick potion } if (itemonground === chest && equippeditem === key) { // open chest } return; } if (equippeditem === potion) { // set potion on ground } if (equippeditem === torch) { // set out torch , drop on ground } if (standingonstaircase && equippeditem === key) { // move downwards 1 level } }
the above illustration code in game doaction function contains 50 or more conditions. knowing in order set them has become issue every new thing i've added. problem different combinations more or less unique things.
how can refactor in improve way? there specific design pattern can use?
it seems break downwards separate functions based on top level decision in case looks user standing.
function doaction() { if (standingonground) { doongroundaction(); } else if (standingonitem) { doonitemaction(); } else { dobasicaction(); } }
then can have map of actions based on other variables:
// map of item on ground , item equipped. var groundactions = { potion: { potion: function () {}, torch: function () {} }, chest: { key: function () { // open chest. } } }; function dogroundaction() { // if there action defined in map execute it, otherwise // perform default action. if (groundactions[itemonground] && groundactions[itemonground][equippeditem]) { groundactions[itemonground][equippeditem](); } else { // default action. } }
javascript refactoring conditional condition conditional-statements
No comments:
Post a Comment