Configuration files hold text, but programs want numbers, booleans and null. Turn each value into the right type.
What to build
A program that reads key=value lines, gives each value a type and prints them.
Requirements
- Write
parseValue(text: string): string | number | boolean | null:trueandfalsebecome booleans,nullbecomes null, text that is a number becomes a number, and anything else stays a string. - Collect the settings in a
Record<string, string | number | boolean | null>. - Print
key: TYPE = VALUEfor each key in alphabetical order, where TYPE isnullfor null and otherwise typeof, and VALUE is the value as String() shows it. - Then print
JSON:followed byJSON.stringifyof the settings, keys in input order.
Input
Line 1: n. Then n lines key=value; keys are distinct words of lowercase letters; values may be empty.
Output
n lines, then the JSON line.
Constraints
1 ≤ n ≤ 30.
Example
Input:
4
port=8080
host=localhost
debug=true
proxy=null
Output:
debug: boolean = true
host: string = localhost
port: number = 8080
proxy: null = null
JSON: {"port":8080,"host":"localhost","debug":true,"proxy":null}
Why it works
A union return type lists every kind of value the parser can produce, so code using a setting must handle each one, and Number() alone would wrongly turn an empty value into 0, which is why empty text is checked first.
Examples
4 port=8080 host=localhost debug=true proxy=null
debug: boolean = true
host: string = localhost
port: number = 8080
proxy: null = null
JSON: {"port":8080,"host":"localhost","debug":true,"proxy":null}
3 rate=0.25 name= verbose=false
name: string =
rate: number = 0.25
verbose: boolean = false
JSON: {"rate":0.25,"name":"","verbose":false}
Hints
Hint 1
Write a function parseValue(text: string): string | number | boolean | null.
Hint 2
A value is a number if Number(text) is not NaN and the text is not empty.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
function parseValue(text: string): string | number | boolean | null {
if (text === "true") return true;
if (text === "false") return false;
if (text === "null") return null;
if (text.trim() !== "" && !Number.isNaN(Number(text))) return Number(text);
return text;
}
const n = Number(read());
const settings: Record<string, string | number | boolean | null> = {};
for (let i = 0; i < n; i++) {
const line = read();
const at = line.indexOf("=");
settings[line.slice(0, at)] = parseValue(line.slice(at + 1));
}
for (const key of Object.keys(settings).sort()) {
const value = settings[key];
const type = value === null ? "null" : typeof value;
console.log(key + ": " + type + " = " + String(value));
}
console.log("JSON: " + JSON.stringify(settings));
Lesson: Basic types: primitives, arrays, tuples and unknown →