DEV Community

Discussion on: Post an Elegant Code Snippet You Love.

Collapse
 
tqbit profile image
tq-bit • Edited

I find using nested hashmaps instead of if-else statements rather elegant when running decision based flows.

I've recently refactored a codebase with a lot of nested if-else control flows using this method. Said project is now much easier to read since decision logic is abstracted from the function using it.

What I also like is that it's easier to type your decision map with jsdoc or ts.

Example

const sequenceMap = Object.freeze({
  admin: {
    authorized: {
        action: () => console.log("Logged in as admin")
    }, 
    notAuthorized: {
        action: () => console.log("Could not login admin!")
    }
  },
  user: {
    authorized: {
        action: () => console.log("Logged in as user")
    }, 
    notAuthorized: {
        action: () => console.log("Could not login user!")
    }
  }
});

const runSequenceAction = (role, auth) => {
    return sequenceMap[role][auth].action();
}

runSequenceAction('admin', 'authorized');
Enter fullscreen mode Exit fullscreen mode

Same functionality with if-else

function runAuthAction(role, auth) {
  if(role === "admin") {
    if(auth === "authorized") {
        console.log("Logged in as admin");
    } else if (auth === "unauthorized") {
        console.log("Could not login admin!")
    }
  } else if (role === "user") {
    if(auth === "authorized") {
        console.log("Logged in as user");
    } else if (auth === "unauthorized") {
        console.log("Could not login user")
    }
  }
}
Enter fullscreen mode Exit fullscreen mode