Master JavaScript

A settings file with two kinds of missing

A settings file with two kinds of missing

Almost every program is configured by a plain text file of name=value lines. You are writing the part that reads one, and the interesting question is what to say when the name is not there.

A setting that is present but blank and a setting that is absent altogether are two different situations, and a program that muddles them will fall back to a default when it should not. That is the null and undefined distinction, made concrete.

What the file looks like

# the server
port=8080
host=localhost
user=
Lines separated by newlines, arriving as one piece of text.

Blank lines are ignored. A line whose first character is # is a comment and is ignored. Every other line has a = in it; everything before the first = is the name and everything after it is the value, even if that includes more = characters.

What to return

  • If the name is present, return its value. A name with nothing after the = returns the empty string.
  • If the name is not present anywhere, return the nine characters undefined.
  • If the same name appears more than once, the last one wins, which is how nearly every real settings file behaves.

Worked example

key = "port"    ->  "8080"
key = "host"    ->  "localhost"
key = "user"    ->  ""           present, and blank
key = "timeout" ->  "undefined"  not there at all
Four lookups against the file above.

Constraints

  • source is at most 2000 characters, with lines separated by a single newline. It may be empty.
  • Names and values have no spaces at either end, but a line may be indented, so trim each line before reading it.
  • key is between 1 and 40 characters and contains no =.
  • A line with no = in it at all is ignored.
Code

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