Options objects let callers give only what they change. Fill in the rest from defaults, with the types saying which is which.
What to build
A program that reads some options and prints all of them, with defaults filled in.
Requirements
- Declare
interface Options { width: number; height: number; title: string; resizable: boolean }. - Write
withDefaults(given: Partial<Options>): Required<Options>with the defaults width 800, height 600, titleUntitledand resizable false. - Read
key=valuelines into aPartial<Options>(numbers for width and height,true/falsefor resizable), then printwidth: W,height: H,title: Tandresizable: R. - A line with any other key prints
unknown option KEYand is ignored.
Input
Line 1: n. Then n lines key=value.
Output
Any unknown option lines, then four lines.
Constraints
0 ≤ n ≤ 10.
Example
Input:
2
title=Editor
width=1024
Output:
width: 1024
height: 600
title: Editor
resizable: false
Why it works
Partial says the caller may leave anything out, and Required promises that the result has every field, so the code after withDefaults never has to check for missing options.
Examples
Example 1 · Input
2 title=Editor width=1024
Expected output
width: 1024 height: 600 title: Editor resizable: false
Example 2 · Input
2 resizable=true colour=red
Expected output
unknown option colour width: 800 height: 600 title: Untitled resizable: true
Hints
Hint 1
function withDefaults(given: Partial<Options>): Required<Options> can spread the defaults and then the given values.
Hint 2
Only put a key into the given object when its line appears.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
interface Options {
width: number;
height: number;
title: string;
resizable: boolean;
}
const DEFAULTS: Required<Options> = { width: 800, height: 600, title: "Untitled", resizable: false };
function withDefaults(given: Partial<Options>): Required<Options> {
return { ...DEFAULTS, ...given };
}
const given: Partial<Options> = {};
const n = Number(read());
for (let i = 0; i < n; i++) {
const line = read();
const at = line.indexOf("=");
const key = line.slice(0, at);
const value = line.slice(at + 1);
if (key === "width" || key === "height") given[key] = Number(value);
else if (key === "title") given.title = value;
else if (key === "resizable") given.resizable = value === "true";
else console.log("unknown option " + key);
}
const options = withDefaults(given);
console.log("width: " + options.width);
console.log("height: " + options.height);
console.log("title: " + options.title);
console.log("resizable: " + options.resizable);