Skip to content

Commit aaee744

Browse files
committed
Add implementation with observer
1 parent 6a58198 commit aaee744

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

JavaScript/4-observer.js

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
'use strict';
2+
3+
const { EventEmitter } = require('events');
4+
const { max } = Math;
5+
6+
const ee = new EventEmitter();
7+
8+
const cities = [];
9+
10+
const variables = {
11+
maxDensity: 0,
12+
count: 0,
13+
};
14+
15+
ee.on('city', city => {
16+
variables.count++;
17+
variables.maxDensity = max(variables.maxDensity, city.density);
18+
cities.push(city);
19+
cities.forEach(city => {
20+
city.relative = Math.round(city.density * 100 / variables.maxDensity);
21+
});
22+
console.table(variables);
23+
console.table(cities);
24+
});
25+
26+
ee.emit('city', {
27+
city: 'Shanghai',
28+
population: 24256800,
29+
area: 6340,
30+
density: 3826,
31+
country: 'China',
32+
});
33+
34+
ee.emit('city', {
35+
city: 'Beijing',
36+
population: 21516000,
37+
area: 16411,
38+
density: 1311,
39+
country: 'China',
40+
});
41+
42+
ee.emit('city', {
43+
city: 'Delhi',
44+
population: 16787941,
45+
area: 1484,
46+
density: 11313,
47+
country: 'India',
48+
});

0 commit comments

Comments
 (0)