Viper
Viper

Reputation: 13

Make a vscode snippet for switch with number of cases

I'm looking for a way to make a snippet for a switch where you can say how many cases you want. Like: switch2 gives

switch (variable) {
    case "value":
        # code...
        break;
    case "value":
        # code...
        break;
    default:
        # code...
        break;
}

and switch3 gives

switch (variable) {
    case "value":
        # code...
        break;
    case "value":
        # code...
        break;
    case "value":
        # code...
        break;
    default:
        # code...
        break;
}

is this even possible and if yes how?

Upvotes: 1

Views: 771

Answers (1)

Mark
Mark

Reputation: 182401

You can do this in an interesting way with regular snippets. You don't trigger it with something like switch3 or switch4 but some generic switch trigger and then you enter how many case statements you want. Not as a single number, like 3 or 4 but by the number of characters you input - can be any characters like .... for four case statements or 1234 for four case statements.

Here is the snippet (in your snippets.json):

"n case switch statement": {
  // "scope": "javascript,typescript",
  "prefix": "switchN",             // whatever prefix you want
  "body": [
    "switch ($2) {",
    "${1/(.)/\tcase \"value\":\n\t\t# code\n\t\tbreak;\n/g}}"
  ]
}

demo of snippet for n cases in a switch statement

[Adapted from https://stackoverflow.com/questions/61046868/multiple-if-else-statements-with-different-variables-vscode-snippet/61050519#61050519.]

Upvotes: 1

Related Questions