Merge Defaults With User Config
NodeJS
Medium
4 views
Problem Description
Merge user config JSON into defaults and print final JSON.
Input Format
stdin: JSON object.
Output Format
Print JSON.
Sample Test Case
Input:
{\"theme\":\"dark\"}
Output:
{ \"site\": \"meetcode\", \"theme\": \"dark\" }
Constraints
If parse fails, use defaults only.
Official Solution
const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim();
const defaults = { site: 'meetcode', theme: 'light' };
let user = {};
try {
user = input ? JSON.parse(input) : {};
} catch (e) {
user = {};
}
const out = { ...defaults, ...(user && typeof user === 'object' ? user : {}) };
console.log(JSON.stringify(out, null, 2));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!