Store contacts as objects with an optional property and print them as cards.
What to build
A program that reads contacts and prints one line for each.
Requirements
- Declare an interface
Contactwithname,phoneand an optionalemail. - Leave
emailout of the object when its field is empty. - Print
NAME - PHONE - EMAIL, with(no email)when there is none, in the input order.
Input
Line 1: n. Then n lines name;phone;email (the email may be empty).
Output
n lines.
Constraints
1 ≤ n ≤ 50.
Example
Input:
2
Ada;555-0101;ada@example.com
Alan;555-0199;
Output:
Ada - 555-0101 - ada@example.com
Alan - 555-0199 - (no email)
Why it works
An optional property says in the type that some contacts have no email, so the printing code is forced to decide what to show when it is missing.
Examples
Example 1 · Input
2 Ada;555-0101;ada@example.com Alan;555-0199;
Expected output
Ada - 555-0101 - ada@example.com Alan - 555-0199 - (no email)
Example 2 · Input
1 Grace Hopper;555-1906;grace@navy.example
Expected output
Grace Hopper - 555-1906 - grace@navy.example
Hints
Hint 1
Declare interface Contact { name: string; phone: string; email?: string }.
Hint 2
An empty email field means the property is left out; print (no email) with ??.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
interface Contact {
name: string;
phone: string;
email?: string;
}
const n = Number(read());
const contacts: Contact[] = [];
for (let i = 0; i < n; i++) {
const [name, phone, email] = read().split(";");
const contact: Contact = { name, phone };
if (email) contact.email = email;
contacts.push(contact);
}
for (const c of contacts) console.log(c.name + " - " + c.phone + " - " + (c.email ?? "(no email)"));