Search code examples
javascriptjavascript-objects

Replace a switch statement with multiple assignments to object literal


I have a switch statement that I'd like to replace with an object literal but because multiple assignments are made for each case, I don't know how to do it.

switch (roll1) {
    case 21:
        rain = 1.25;
        break;
    case 22:
        rain = 1.5;
        solid = "light";
        break;
    case 23:
        rain = 1.75;
        solid = "light";
        break;
    case 24:
        rain = 2;
        solid = "light";
        break;
    case 25:
        rain = 2.25;
        solid = "medium";
        break;
    case 26:
        rain = 2.5;
        solid = "medium";
        hook = 1;
        break;
    case 27:
        rain = 2.75;
        solid = "medium";
        hook = 5;
        break;
    case 28:
        rain = 3;
        solid = "heavy";
        hook = 10;
        break;
    case 29:
        rain = 3.25;
        solid = "heavy";
        hook = 15;
        break;
    case 30:
        rain = 3.5;
        solid = "heavy";
        hook = 20;
}
return [rain,solid,hook];

Note: solid & hook are given default values before the switch statement. I was looking at this example:

const dogSwitch = (breed) => ({
  "border": "Border Collies are good boys and girls.",
  "border2": "Border Collies are good boys and girls.",
  "pitbull": "Pit Bulls are good boys and girls.",
  "german": "German Shepherds are good boys and girls."
})[breed]
console.log(dogSwitch("border2"))

But each line of the object literal only assigns one value, not multiple. Please advise.


Solution

  • You can define object like below and then use Object destructuring to retrieve values for specified variables:

    let doc = { 23: { rain: 1.25 }, 22: { rain: 1.5, solid: "light" }, 29: { rain: 3.25, solid: "heavy", hook: 20 } };
    
    let {rain, solid, hook} = doc[29];
    
    console.log(solid);
    console.log(rain);
    console.log(hook);