StringUtil { public final static String removeComments(String code) { State state = State.NORMAL; StringBuilder result = new StringBuilder(); Map<String, Character> replacements = new HashMap<>(); Scanner scanner = new Scanner(normalize(code, replacements)); scanner.useDelimiter(""); while (scanner.hasNext()) { String character = scanner.next(); switch (state) { case NORMAL: if (character.equals("/") && scanner.hasNext()) { String nextCharacter = scanner.next(); if (nextCharacter.equals("/")) { state = State.IN_LINE_COMMENT; } else if (nextCharacter.equals("*")) { state = State.IN_BLOCK_COMMENT; } else { result.append(character).append(nextCharacter); } } else { result.append(character); if (character.equals("\"")) { state = State.IN_STRING; } } break; case IN_STRING: result.append(character); if (character.equals("\"")) { state = State.NORMAL; } else if (character.equals("\\") && scanner.hasNext()) { result.append(scanner.next()); } break; case IN_LINE_COMMENT: if (character.equals("\n")) { result.append(character); state = State.NORMAL; } break; case IN_BLOCK_COMMENT: if (character.equals("*") && scanner.hasNext() && scanner.next().equals("/")) { state = State.NORMAL; break; } } } scanner.close(); String handled = result.toString(); for (Entry<String, Character> entry : replacements.entrySet()) { handled = handled.replace(entry.getKey(), String.valueOf(entry.getValue())); } return handled; }  final static String removeComments(String code);  }
@Test public void commentRemoval_handlesCommentsCorrectly() { String singleLineBlock = StringUtil .removeComments("return html'';"); Assert.assertEquals("return html'';", singleLineBlock); String blockComment = StringUtil .removeComments("return html'';"); Assert.assertEquals("return html'';", blockComment); String newLineSingleBlock = StringUtil .removeComments("return html'';"); Assert.assertEquals("return html'';", newLineSingleBlock); String noComments = "<vaadin-text-field label=\"Nats Url(s)\" placeholder=\"nats: Assert.assertEquals(noComments, StringUtil.removeComments(noComments)); String lineComment = StringUtil .removeComments("return html' Assert.assertEquals("return html'\n';", lineComment); String mixedComments = StringUtil.removeComments( "return html'\nCode; + "';"); Assert.assertEquals("return html'\nCode;\n';", mixedComments); }
@Test public void commentRemoval_emojiInString_removalDoesnotThrowResultIsTheSame() { String initialTemplate = "import { html } from '@polymer/polymer/lib/utils/html-tag.js';\n" + "class EmployeeForm extends PolymerElement {\n" + " static get template() {\n" + " return html`\n" + " <div style=\"width: 100%; height: 100%;\" class=\"scroll-div\"> \n" + " <iron-pages selected=\"[[page]]\"> \n" + " <page>\n" + "🚧 Training: Coming soon 🚧\n" + "</page> \n" + " </iron-pages> \n" + " </div> \n" + "`;\n" + " }\n" + "\n"; String template = StringUtil.removeComments(initialTemplate); Assert.assertEquals(initialTemplate, template); }