1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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, });
}
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;
}
}
|