-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5-collaborative.js
More file actions
88 lines (66 loc) · 1.49 KB
/
5-collaborative.js
File metadata and controls
88 lines (66 loc) · 1.49 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict';
class Document {
constructor() {
this.content = [];
}
applyEdit(edit) {
this.content.push(edit);
}
getContent() {
return this.content.join('');
}
}
// Mediator
class Editor {
constructor() {
this.users = new Map();
this.document = new Document();
}
addUser(user) {
this.users.set(user.id, user);
user.setMediator(this);
}
removeUser(user) {
this.users.delete(user.id);
}
receiveEdit(userId, edit) {
if (!this.users.has(userId)) return;
this.document.applyEdit(edit);
const content = this.document.getContent();
for (const [id, user] of this.users) {
if (id !== userId) user.receiveUpdate(content);
}
}
getContent() {
return this.document.getContent();
}
}
class User {
constructor(id, name) {
this.id = id;
this.name = name;
this.mediator = null;
}
setMediator(mediator) {
this.mediator = mediator;
}
makeEdit(edit) {
if (this.mediator) {
console.log(`${this.name} edits: "${edit}"`);
this.mediator.receiveEdit(this.id, edit);
}
}
receiveUpdate(content) {
console.log(`${this.name} sees updated document: "${content}"`);
}
}
// Usage
const editor = new Editor();
const user1 = new User(1, 'Marcus');
const user2 = new User(2, 'Lucius');
editor.addUser(user1);
editor.addUser(user2);
console.log('Initial Document:', editor.getContent());
user1.makeEdit('Hello ');
user2.makeEdit('World!');
console.log('Final Document:', editor.getContent());