4
\$\begingroup\$

I have this program that takes two strings from the user, stores them in mixArray, then "mixes" them with mixItUp() and outputs a bit of flavor text, depending on the combination. Duplicate combinations (red-blue, blue-red) also give the same outcome.

I've gotten to a nested switch statement that's miles shorter than my previous tries, but I'm trying figure out if there's a more optimal, or readable method to do this, since I intend to scale it up.

mixItUp() {
  this.mixArray.sort();            // Sorts the array
  switch (this.mixArray[0]) {      // Goes through the first object
    case "blue":
      switch (this.mixArray[1]) {  // Goes through the second if the first is "blue"
        case "green":
          console.log("bf");
          break;
        case "purple":
          console.log("bg");
          break;
        case "yellow":
          console.log("bp");
          break;
        default:
          console.log("??");
          break;
      }
      break;
    case "green":     // If [0] is "green"...
      switch (this.mixArray[1]) {
        case "purple":
          console.log("fg");
          break;
        case "yellow":
          console.log("fp");
          break;
        default:
          console.log("??");
          break;
      }
      break;
    case "purple":     // If [0] is "purple"...
      switch (this.mixArray[1]) {
        case "yellow":
          console.log("gp");
          break;
        default:
          console.log("??");
          break;
      }
      break;
    default:
      break;
  }
}
\$\endgroup\$
  • 2
    \$\begingroup\$ Can you provide more context - what is the purpose of this code? See How do I ask a Good Question?, where you will find advice for titling your question, too. \$\endgroup\$ – greybeard Jan 14 at 22:55
  • 1
    \$\begingroup\$ The simplest fix I can think of would be to define the output strings in a single const object like so : const colors = { "red" : { "red" : "a", "blue" : "b", "green" : "c" }, "green" : { "red" : "x", "blue" : "y", "green" : "z" } }; then you can access them like this str["red"]["blue"]. I'd also recommend you make the function return a string which you then print in the program, rather than printing the output directly from the function; this makes it more flexible and easier to adapt/modify later. \$\endgroup\$ – cliesens Jan 14 at 22:59
  • \$\begingroup\$ Thanks, @cliesens! Didn't even think of using a json object, but this works wonderfully and is way easier to read and change. Kudos! \$\endgroup\$ – zri5004 Jan 15 at 12:53
2
\$\begingroup\$

It seems this could be simplified with a small lookup table and then concatenating strings. Using a table as simple as:

const lookup = {
  blue: 'b',
  green: 'f',
  purple: 'g',
  yellow: 'p'
};

we can then lookup the color values and concatenate them together. Combined with a simple check to make sure the color is valid and the 2 colors aren't the same, and it seems to produce the same result.

Here's the full function:

mixItUp: function() {
  this.mixArray.sort();
  const lookup = {
    blue: 'b',
    green: 'f',
    purple: 'g',
    yellow: 'p'
  };

  let mix;
  const color1 = lookup[this.mixArray[0]];
  const color2 = lookup[this.mixArray[1]];

  if (color1 && color2 && (color1 !== color2)) {
    mix = `${color1}${color2}`;
  } else {
    mix = '??';
  }

  return mix;
}

And here it is in action:

function createMix(color1, color2) {
  return {
    mixArray: [color1, color2],
    mixItUp: function() {
      this.mixArray.sort();
      const lookup = {
        blue: 'b',
        green: 'f',
        purple: 'g',
        yellow: 'p'
      };

      let mix;
      const color1 = lookup[this.mixArray[0]];
      const color2 = lookup[this.mixArray[1]];
      
      if (color1 && color2 && (color1 !== color2)) {
        mix = `${color1}${color2}`;
      } else {
        mix = '??';
      }

      return mix;
    }
  }
}


// Handle the form
const form = document.getElementById('mixitup');

form.addEventListener('submit', event => {
  event.preventDefault();
  const color1 = document.getElementById('color1').value;
  const color2 = document.getElementById('color2').value;

  const mixedArray = createMix(color1, color2)
  console.log(mixedArray.mixItUp())
})
<form id="mixitup">
  <select id="color1">
    <option value="">Select...</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
    <option value="purple">Purple</option>
    <option value="yellow">Yellow</option>
  </select>
  <select id="color2">
    <option value="">Select...</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
    <option value="purple">Purple</option>
    <option value="yellow">Yellow</option>
  </select>
  <input type="submit" value="Mix it up!">
</form>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.