Search code examples
visual-studio-codecode-snippetsvscode-snippets

multiple if/else statements with different variables: vscode snippet


I'm trying to write a snippet to make case-style statements in JavaScript quicker. Right now I have this, and it works:

    "long if-else": {
        "scope": "javascript,typescript,html",
        "prefix": "ie",
        "body": [
            "if ( $2 ) {\n\n} ${1/(.)/else if ( ) {\n\n} /g}else {\n\n}\n"
        ]
    }

it allows you to insert 0 or more else if statements in between the opening if and closing else by entering n characters after first tab and hitting tab again.

I would like the user (me) to be able to specify a value to go inside the brackets (like myVar =). I've tried setting up a variable to be evaluated after the transform, but it hasn't been read as a variable.


Solution

  • You can't put a tabstop or another variable inside the replacement part of a transform.

    You have to use a different approach if you want each if/else block to contain a different variable, like:

    if (myVar == ) {
    
    } else if (myVar == a) {
    
    } else if (myVar == b) {
    
    } else if (myVar == c) {
    
    } else if (myVar == d) {
    
    } else {
    
    }
    

    You have to list those variables first before generating each else if block. Try this snippet:

    "long if-else": {
      "scope": "javascript,typescript,html",
      "prefix": "ie",
      "body": [
    
        "if (myVar = $2) {\n",
    
        "${1/(\\w+)(,\\s*|\\b)/} else if (myVar = $1) {${2:?\n\n:\n}/g}",
    
        "} else {",
        "",
        "}",
        "$3"
      ]
    },
    

    Here is a demo to see how you input the variables:

    enter image description here


    You enter each of the myVar's as a comma-separated list and then Tab. It doesn't handle the zero-case though without some more complications.