Master JavaScript

Taking the comments out

Taking the comments out

Before a program is sent to a browser it is usually shrunk, and the first thing a shrinker throws away is the comments, because the engine ignores them anyway. You are writing the simplest useful version of that step.

Given the text of a file, remove every // comment and hand back what is left.

The rules

  1. In each line, remove everything from the first // onwards, including the slashes themselves.
  2. Remove any spaces left at the end of the line.
  3. Drop the line entirely if there is nothing left of it.
  4. Join the surviving lines back together with a single newline between them.

Worked example

Input:
  // set the price
  const price = 20;   // in pounds
  console.log(price);

Line by line:
  "// set the price"           ->  ""                     dropped
  "const price = 20;   // ..." ->  "const price = 20;"    kept, spaces trimmed
  "console.log(price);"        ->  "console.log(price);"  kept unchanged

Output:
  const price = 20;
  console.log(price);
Three lines in, two out.

Constraints

  • source is at most 4000 characters, with lines separated by a single newline. It may be empty, and the answer for an empty input is the empty string.
  • No line contains // inside a piece of quoted text, so you never have to tell a comment from a web address. A real shrinker does have to, which is why real ones contain a parser.
  • Only // comments appear. There are no /* */ blocks.
  • Spaces at the start of a line are left exactly as they are. Only trailing spaces are removed.
  • If every line is dropped, the answer is the empty string, with no stray newline.
Code

Run your code to see how it does on the examples. Submit also runs the hidden cases.