I have a rather repetitive switch case statement and in my quest to learn the simplest way of doing things, I wanted to turn to SO and see if there is a more elegant solution to the following:
switch(id)
{
case 'ib-02a':
if(direction == 'left')
setHash('ib-02b');
break;
case 'ib-02b':
if(direction == 'right')
setHash('ib-02a');
if(direction == 'left')
setHash('ib-02c');
break;
case 'ib-02c':
if(direction == 'right')
setHash('ib-02b');
if(direction == 'left')
setHash('ib-02d');
break;
case 'ib-02d':
if(direction == 'right')
setHash('ib-02c');
break;
case 'ib-03a':
if(direction == 'left')
setHash('ib-03b');
break;
case 'ib-03b':
if(direction == 'right')
setHash('ib-03a');
if(direction == 'left')
setHash('ib-03c');
break;
case 'ib-03c':
if(direction == 'right')
setHash('ib-03b');
if(direction == 'left')
setHash('ib-03d');
break;
case 'ib-03d':
if(direction == 'right')
setHash('ib-03c');
break;
case 'pb-05a':
if(direction == 'left')
setHash('pb-05b');
break;
case 'pb-05b':
if(direction == 'right')
setHash('pb-05a');
if(direction == 'left')
setHash('pb-05c');
break;
case 'pb-05c':
if(direction == 'right')
setHash('pb-05b');
if(direction == 'left')
setHash('pb-05d');
break;
case 'pb-05d':
if(direction == 'right')
setHash('pb-05c');
break;
}
I’m reading swipe events, and if the ID of the element I am swiping on matches either ib-02*, ib-03*, or pb-05*, I am calling a setHash function for the appropriate ID. If I’m swiping on *a, I swipe left to *b. If I’m swiping on *b, I swipe right to *a and left to *c. So on and so forth, always between *a and *d.
There must be a less repetitive way to do this, but I’m not sure exactly what the best approach is.
How about mapping them to an object? Then just use the
setHashwith the retrieved value.It’s all retrieval and no condition evaluation, which can be good for performance.