Home > Net >  How to compact a bunch of repeating case statements?
How to compact a bunch of repeating case statements?

Time:04-22

In my code there are a bunch of repeating case statements, they are almost the same, the only thing changing in every case statement is the argument 'key' from function click(key).

'c' is a JSON. The only problem is that I need to use the argument 'key' inside of the robot.moveMouse() It should have to look something like this: robot.moveMouse(c.Key_x, c.Key_y); But this would take 'key' as a string not an argument. How would I go about doing this?

My Code:

function click(key) {
    if(key == null) return;
    old_pos = robot.getMousePos();
    switch(key) {
        case 'Record': robot.moveMouse(c.Record_x, c.Record_y); break;
        case 'Exit':   robot.moveMouse(c.Exit_x,   c.Exit_y);   break;
        case 'Clear':  robot.moveMouse(c.Clear_x,  c.Clear_y);  break;
        case 'Go':     robot.moveMouse(c.Go_x,     c.Go_y);     break;
        case 'Delete': robot.moveMouse(c.Delete_x, c.Delete_y); break;
        case 'Move':   robot.moveMouse(c.Move_x,   c.Move_y);   break;
        case 'Disk':   robot.moveMouse(c.Disk_x,   c.Disk_y);   break;
    }
    robot.mouseClick();
    robot.moveMouse(old_pos.x, old_pos.y);
}

The JSON body:

{
    "Record_x": 426,
    "Record_y": 256,

    "Exit_x": 582,
    "Exit_y": 540,

    "Clear_x": 702,
    "Clear_y": 500,

    "Go_x": 464,
    "Go_y": 584,

    "Delete_x": 425,
    "Delete_y": 298,

    "Move_x": 505,
    "Move_y": 293,
    
    "Disk_x": 626,
    "Disk_y": 252
}

CodePudding user response:

Just use c like an array:

robot.moveMouse(c[key "_x"], c[key "_y"]);
  • Related