Combine a user's choices with default settings.
What to build
The way most programs handle settings: start with defaults and let the user override some of them.
Requirements
- The defaults are in the starter:
theme,sizeandlang. - Each input line is a JSON object holding a user's choices.
- For each line, print the merged settings with
JSON.stringify. - Each line starts afresh from the defaults. Do not change the
defaultsobject.
Input
Several lines of JSON objects.
Output
One line of JSON per input line.
Constraints
There are from 1 to 50 lines, and each is valid JSON for an object.
Example
Input:
{"theme":"dark"}
Output:
{"theme":"dark","size":14,"lang":"en"}
Why it works
Spread builds a new object every time, so one user's choices cannot leak into the next. The default keys are copied first, so they keep their position, and any extra key is added after them.
Examples
Example 1 · Input
{"theme":"dark"}
Expected output
{"theme":"dark","size":14,"lang":"en"}
Example 2 · Input
{}
Expected output
{"theme":"light","size":14,"lang":"en"}
Hints
Hint 1
{ ...defaults, ...choices } makes a new object, and the later values win.
Hint 2
Never change defaults itself. The next line needs it unchanged.
Hint 3
JSON.parse(line) gives the object for each line.
Solution
Show one correct solution (try it yourself first)
const defaults = { theme: "light", size: 14, lang: "en" };
let line = prompt();
while (line !== null) {
const merged = { ...defaults, ...JSON.parse(line) };
console.log(JSON.stringify(merged));
line = prompt();
}