javascript - Sharing script between different switch case condition -
condition 1 should perform task 1, 2, 3, 4, 5, , 9. condition 2 should perform task 1, 2, 3, 6, 7, , 9. condition 3 should perform task 8 , 9.
the following easy read, not work second condition1
, condition2
tasks not executed earlier break
causes script exit switch statement.
var condition='condition1'; switch(condition) { case 'condition1': case 'condition2': console.log('do task 1'); console.log('do task 2'); console.log('do task 3'); break; case 'condition1': console.log('do task 4'); console.log('do task 5'); break; case 'condition2': console.log('do task 6'); console.log('do task 7'); break; case 'condition3': console.log('do task 8'); break; } console.log('do task 9');
the following should work, not easy read, , become increasingly more difficult more functionality shared between different conditions.
var condition='condition1'; switch(condition) { case 'condition1': case 'condition2': console.log('do task 1'); console.log('do task 2'); console.log('do task 3'); switch(condition) { case 'condition1': console.log('do task 4'); console.log('do task 5'); break; case 'condition2': console.log('do task 6'); console.log('do task 7'); break; } break; case 'condition3': console.log('do task 8'); break; } console.log('do task 9');
again, should work, coming descriptive names different groups problematic.
var condition='condition1'; switch(condition) { case 'condition1': task_group_1_2_3(); task_group_4_5(); break; case 'condition2': task_group_1_2_3(); task_group_6_7(); break; case 'condition3': console.log('do task 8'); break; } console.log('do task 9'); function task_group_1_2_3() { console.log('do task 1'); console.log('do task 2'); console.log('do task 3'); } function task_group_4_5() { console.log('do task 4'); console.log('do task 5'); } function task_group_6_7() { console.log('do task 6'); console.log('do task 7'); }
what cleanest way create switch statement shares script between different case conditions?
you move conditions object , tasks , iterate array task.
you use right name instead of number key name.
var tasks = { 1: function () { console.log(1); }, 2: function () { console.log(2); }, 3: function () { console.log(3); }, 4: function () { console.log(4); }, 5: function () { console.log(5); }, 6: function () { console.log(6); }, 7: function () { console.log(7); }, 8: function () { console.log(8); }, 9: function () { console.log(9); } }, conditions = { 1: [1, 2, 3, 4, 5, 9], 2: [1, 2, 3, 6, 7, 9], 3: [8, 9] }, condition = 1; conditions[condition].foreach(function (a) { tasks[a](); });
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comments
Post a Comment