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 :

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

Leave a Reply