Send messages through different channels, each a class that implements the same interface.
What to build
A program that routes messages to email, SMS and push notifiers.
Requirements
- Declare
interface Notifier { send(to: string, message: string): string }and three classes that implement it. EmailNotifier: iftocontains@, returnemail to TO: MESSAGE; otherwiseemail error: bad address TO.SmsNotifier: iftois only digits, returnsms to TO: M, where M is the message cut to its first 20 characters, with...added if it was longer; otherwisesms error: bad number TO.PushNotifier: returnpush to TO: MESSAGE.- For a channel with no notifier print
no channel CHANNEL.
Input
Line 1: n. Then n lines CHANNEL TO MESSAGE (the message may contain spaces).
Output
n lines.
Constraints
1 ≤ n ≤ 50.
Example
Input:
4
email ada@example.com Your order has shipped
sms 5550101 Your code is 123456, valid for ten minutes
push alan Build finished
fax 555 Hello
Output:
email to ada@example.com: Your order has shipped
sms to 5550101: Your code is 123456,...
push to alan: Build finished
no channel fax
Why it works
The sending code depends only on the Notifier interface, so each channel's rules stay inside its own class and a new channel is one more class in the record.
Examples
Example 1 · Input
4 email ada@example.com Your order has shipped sms 5550101 Your code is 123456, valid for ten minutes push alan Build finished fax 555 Hello
Expected output
email to ada@example.com: Your order has shipped sms to 5550101: Your code is 123456,... push to alan: Build finished no channel fax
Example 2 · Input
2 email nobody Hi sms 555-0101 Hi
Expected output
email error: bad address nobody sms error: bad number 555-0101
Hints
Hint 1
interface Notifier { send(to: string, message: string): string } returns the line to print.
Hint 2
Keep the notifiers in a Record<string, Notifier> keyed by channel name.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
interface Notifier {
send(to: string, message: string): string;
}
class EmailNotifier implements Notifier {
send(to: string, message: string): string {
return to.includes("@") ? "email to " + to + ": " + message : "email error: bad address " + to;
}
}
class SmsNotifier implements Notifier {
send(to: string, message: string): string {
if (!/^\d+$/.test(to)) return "sms error: bad number " + to;
const text = message.length > 20 ? message.slice(0, 20) + "..." : message;
return "sms to " + to + ": " + text;
}
}
class PushNotifier implements Notifier {
send(to: string, message: string): string {
return "push to " + to + ": " + message;
}
}
const notifiers: Record<string, Notifier> = { email: new EmailNotifier(), sms: new SmsNotifier(), push: new PushNotifier() };
const n = Number(read());
for (let i = 0; i < n; i++) {
const [channel, to, ...words] = read().split(" ");
const notifier = notifiers[channel];
console.log(notifier ? notifier.send(to, words.join(" ")) : "no channel " + channel);
}