-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathactor.js
More file actions
57 lines (47 loc) · 1.13 KB
/
actor.js
File metadata and controls
57 lines (47 loc) · 1.13 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
'use strict';
class Point {
#x;
#y;
#queue = [];
#processing = false;
constructor(x, y) {
this.#x = x;
this.#y = y;
}
#move(dx, dy) {
this.#x += dx;
this.#y += dy;
}
#clone() {
return new Point(this.#x, this.#y);
}
#toString() {
return `(${this.#x}, ${this.#y})`;
}
async send(message) {
return new Promise((resolve) => {
this.#queue.push({ ...message, resolve });
this.#process();
});
}
async #process() {
if (this.#processing) return;
this.#processing = true;
while (this.#queue.length) {
const { method, x: dx, y: dy, resolve } = this.#queue.shift();
if (method === 'move') resolve(this.#move(dx, dy));
if (method === 'clone') resolve(this.#clone());
if (method === 'toString') resolve(this.#toString());
}
this.#processing = false;
}
}
// Usage
const main = async () => {
const p1 = new Point(10, 20);
console.log(await p1.send({ method: 'toString' }));
const c1 = await p1.send({ method: 'clone' });
await c1.send({ method: 'move', x: -5, y: 10 });
console.log(await c1.send({ method: 'toString' }));
};
main();