-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path2-abstraction.js
43 lines (36 loc) · 966 Bytes
/
2-abstraction.js
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
'use strict';
const { EventEmitter } = require('node:events');
// Case 2: Active entity
// for example: Collection, Stream, Scheduler
class Collection extends EventEmitter {
constructor() {
super();
this.keys = [];
this.values = [];
}
set(key, value) {
const index = this.keys.indexOf(key);
if (index === -1) {
this.keys.push(key);
this.values.push(value);
} else {
const previous = this.values[index];
this.values[index] = value;
this.emit('rewrite', key, value, previous);
}
}
get(key) {
const index = this.keys.indexOf(key);
if (index === -1) return;
return this.values[index];
}
}
// Usage
const collection = new Collection();
collection.on('rewrite', (key, value, previous) => {
console.log('rewrite', { key, value, previous });
});
collection.set('name', 'Marcus');
collection.set('name', 'Marcus Aurelius');
const name = collection.get('name');
console.dir({ name });