Skip to content

Commit 1b83d3c

Browse files
author
vinogradov
committed
monety
1 parent 4d8b697 commit 1b83d3c

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

task1.js

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
'use strict';
2+
3+
const request = require('request-promise-native');
4+
const mongo = require('mongodb');
5+
6+
const constants = require('./common').constants;
7+
const SUCCESSFUL_EXIT_CODE = 0;
8+
9+
let DB;
10+
11+
async function connect() {
12+
return mongo.connect(constants.CONNECTION_STRING);
13+
}
14+
15+
let reg = '';
16+
17+
for (let year = 1000; year <= 2017; ++year) {
18+
reg += year;
19+
if (year !== 2017) {
20+
reg += '|';
21+
}
22+
}
23+
24+
let hasYears = 0;
25+
let issuedBefore2000 = 0;
26+
27+
function count(item) {
28+
let itemText = item.title;
29+
30+
if (item.advertisementBody) {
31+
itemText += item.advertisementBody;
32+
}
33+
34+
const res = (new RegExp(reg)).exec(itemText);
35+
36+
if (res) {
37+
hasYears++;
38+
39+
if (res[0] < 2000) {
40+
issuedBefore2000++;
41+
}
42+
43+
} else if (/[\d]{2,3}[\s]*-[\s]*[\d]{2,3}[\s]*\u0433/.test(itemText)) {
44+
hasYears++;
45+
issuedBefore2000++;
46+
}
47+
}
48+
49+
async function main(db) {
50+
const task1Collection = db.collection(constants.MAIN_COLLECTION_NAME);
51+
const cursor = await task1Collection.find({is_expired: false});
52+
53+
let item;
54+
while ((item = await cursor.next()) !== null) {
55+
count(item);
56+
}
57+
58+
console.log(hasYears);
59+
console.log(issuedBefore2000);
60+
}
61+
62+
function gracefulExit() {
63+
function exit(error) {
64+
console.log(`Exited gracefully. Errors: ${error}`);
65+
process.exit(SUCCESSFUL_EXIT_CODE);
66+
}
67+
68+
if (DB) {
69+
console.log('Try to close DB connection');
70+
DB.close().then(() => {
71+
console.log('Connection is closed');
72+
exit();
73+
});
74+
} else {
75+
exit();
76+
}
77+
78+
}
79+
80+
81+
(async() => {
82+
try {
83+
DB = await connect();
84+
console.log('mongo connected');
85+
await main(DB);
86+
await DB.close();
87+
} catch (error) {
88+
console.log(error);
89+
gracefulExit();
90+
}
91+
})();
92+
93+
94+
process
95+
.on('SIGINT', () => {
96+
console.log('Got SIGINT. Try to exit gracefully');
97+
gracefulExit();
98+
})
99+
.on('SIGTERM', () => {
100+
console.log('Got SIGTERM. Try to exit gracefully');
101+
gracefulExit();
102+
});

0 commit comments

Comments
 (0)