Nitish Nitish - 4 months ago 22
Javascript Question

Optimize switch case angular

I have following function in my anguar controller, there is a lot of repeatation in switch case, I am not sure how can I optimize it?

$scope.start = function() {

var when;

console.log("Start: " + $scope.level + " " + $scope.round)
switch($scope.level + "|"+ $scope.round){
case "1|1":
$scope.promptRound='Level 1 Round 1';
when=3000
break;
case "1|2":
$scope.promptRound='Level 1 Round 2';
when=3000
break;
...
case "2|1":
$scope.promptRound='Level 2 Round 1';
when=3000
break;
case "2|2":
$scope.promptRound='Level 2 Round 2';
when=3000
break;
...
default:
$scope.promptRound='Default';
}


The cases goes on till
case "6|8"
Essentially there are several levels identified by $scope.level and each level has several rounds (each level has different number of rounds) identified by $scope.round.

Answer

How about this instead switch?

$scope.promptRound = $scope.level && $scope.round 
  ? ['Level', $scope.level, 'Round', $scope.round].join(' ')
  : 'Default';

var when = $scope.level && $scope.round ? 3000 : null;

or

if($scope.level && $scope.round) {
  var when = 3000;
  $scope.promptRound = ['Level', $scope.level, 'Round', $scope.round].join(' ');
} else {
  $scope.promptRound = 'Default'; 
}