export class Messages { constructor() { this.channels = {}; } inChannel(channel) { return this.channels[channel] = (this.channels[channel] || []); } addMessage(channel, id, at, sender, body) { this.updateChannel(channel, (messages) => [...messages, { id, at, sender, body }]); return this; } setMessages(messages) { this.channels = {}; for (let { channel, id, at, sender, body } of messages) { this.inChannel(channel).push({ id, at, sender, body, }); } for (let channel in this.channels) { this.channels[channel].sort((a, b) => a.at - b.at); } return this; } deleteMessage(message) { for (let channel in this.channels) { this.updateChannel(channel, (messages) => messages.filter((msg) => msg.id != message)); } return this; } deleteChannel(id) { delete this.channels[id]; return this; } updateChannel(channel, callback) { let messages = callback(this.inChannel(channel)); messages.sort((a, b) => a.at - b.at); this.channels[channel] = messages; } }