skip to Main Content

i got a project has 3 users roles (parent – child – teacher) and each role has 2 different statues (booked – unbooked) that changes the UI and logic.

Example:-
the home header in the home page will be change based on the user role and the statues.

How to solve this problem without big chain of conditions ?

Wrong Answer ❌

  switch (userRole) {
    case 'parent':
      switch (status) {
        case 'booked':
          return // BookedParentComponent
        case 'unbooked':
          return // UnBookedParentComponent
      }

    case 'child':
      switch (status) {
        case 'booked':
          return // BookedChildComponent
        case 'unbooked':
          return // UnBookedChildComponent
      }

    case 'teacher':
      switch (status) {
        case 'booked':
          return // BookedTeacherComponent
        case 'unbooked':
          return // UnBookedTeacherComponent
      }
  }

2

Answers


  1. You can use a map/object,

    function returnComponent(userRole, status) {
      const components = {
        "parent-booked": BookedParentComponent,
        "parent-unbooked": UnBookedParentComponent,
        "child-booked": BookedChildComponent,
        "child-unbooked": UnBookedChildComponent,
        "teacher-booked": BookedTeacherComponent,
        "teacher-unbooked": UnBookedTeacherComponent,
      };
    
      return components[userRole + "-" + status];
    }
    
    
    // use it like this
    returnComponent('parent', 'booked');
    
    Login or Signup to reply.
  2. You can define a nested object structure that maps the userRole and status to the correct component. This avoids the need for multiple switch or if statements and makes the code cleaner and more maintainable.
    
     const componentMap = {
      parent: {
        booked: 'BookedParentComponent',
        unbooked: 'UnBookedParentComponent',
      },
      child: {
        booked: 'BookedChildComponent',
        unbooked: 'UnBookedChildComponent',
      },
      teacher: {
        booked: 'BookedTeacherComponent',
        unbooked: 'UnBookedTeacherComponent',
      },
    };
    
    function getComponent(userRole, status) {
      // Return the appropriate component based on the role and status
      return componentMap[userRole]?.[status] || null; // Fallback to null if no match
    }
    
    // Usage example
    const component = getComponent('parent', 'booked');
    console.log(component); // Output: BookedParentComponent
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search