Master JavaScript

A linter for lines that will be swallowed

A linter for lines that will be swallowed

Your team has decided to write JavaScript without semicolons. That is a workable choice, and it comes with one obligation: any line that begins with certain characters has to be given a leading semicolon, or the parser will join it to the line above.

You are writing the check that runs before every commit. Given the text of a file, count how many lines are exposed.

Which lines count

Split the text into lines. A line is exposed when all three of these are true.

  • It is not the very first line, because there is nothing above it to be joined to.
  • It is not blank, meaning it has at least one character that is not a space.
  • Its first character that is not a space is one of (, [, a backtick, + or -.

Worked example

const sum = a + b
(a + b).toString()
console.log(sum)

  line 1  const sum = a + b        first line, skipped
  line 2  (a + b).toString()       starts with (   counts
  line 3  console.log(sum)         starts with c   no

Output: 1
Three lines, one of them exposed.

Line 2 is the one that matters. Without a semicolon at the end of line 1, the parser reads a + b(a + b) and the program fails at run time with a message about calling something that is not a function.

The awkward ends

Input:  ""                          Output: 0
Input:  "(1).toString()"             Output: 0    the only line is the first
Input:  "let a = 1\n\n   [0]"        Output: 1    blank line skipped, spaces ignored
An empty file, a single line, and indentation.

Constraints

  • source is at most 4000 characters, with lines separated by a single newline. It may be empty.
  • Only the five characters listed above count. The lesson names six; this exercise leaves out / on purpose, because telling a comment from a division needs a real parser.
  • Leading spaces are ignored when looking for the first character.
  • Return the number of exposed lines, which is 0 when there are none.
Code

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