Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Switch Statement: Applying Multiple Arguments in One Output

I am trying to figure out how I can apply two different conditions to one output in a switch statement. For example, I have a function to style a string depending on what arguments that 2nd parameter gets. The first and second output is okay since it only has one argument for styling but the third output does. I cannot find a way to apply both uppercase and reversed styling to a string. I’ve tried to loop a switch statement. I’d like to know if there are any good solutions for this.

function caseStyle(string, style) {
  function toUpper(string) {
    string = string.toUpperCase();
    return string;
  }

  function toReversed(string) {
    string = string.split("").reverse().join("");
    return string;
  }

  switch (style) {
    case "upper":
      string = toUpper(string);
      break;
    case "reversed":
      string = toReversed(string);
      break;
  }
  return string;
}

console.log(caseStyle("hello", "upper")); //output: HELLO
console.log(caseStyle("hello", "reversed")); //output: olleh
console.log(caseStyle("hello", ["upper", "reversed"])); // expected output: OLLEH

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

you’d need to check if style is an array, and handle accordingly

Or, force it to be an Array style = [style].flat() and then iterate that array

The .flat() will flatten the array in the case when an array is passed in

as follows

function caseStyle(string, style) {
  style = [style].flat();
  function toUpper(string) {
    string = string.toUpperCase();
    return string;
  }

  function toReversed(string) {
    string = string.split("").reverse().join("");
    return string;
  }
  style.forEach(style => {
    switch (style) {
      case "upper":
        string = toUpper(string);
        break;
      case "reversed":
        string = toReversed(string);
        break;
    }
  });
  return string;
}

console.log(caseStyle("hello", "upper")); //output: HELLO
console.log(caseStyle("hello", "reversed")); //output: olleh
console.log(caseStyle("hello", ["upper", "reversed"])); // expected output: OLLEH
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading