dayuser.js
2.99 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
const _ = require('lodash');
const readline = require('readline');
const fs = require('fs');
const dayjs = require('dayjs');
let stat = fs.statSync('/Users/chenfeng/Downloads/buyers.csv');
let totalSize = stat.size;
let passedLength = 0;
let lastSize = 0;
let startTime = Date.now();
setTimeout(function show() {
let percent = Math.ceil((passedLength / totalSize) * 100);
let size = Math.ceil(passedLength / 1000000);
let diff = size - lastSize;
lastSize = size;
console.log('已完成' + size + 'MB, ' + percent + '%, 速度:' + diff * 2 + 'MB/s');
if (passedLength < totalSize) {
setTimeout(show, 500);
} else {
let endTime = Date.now();
console.log();
console.log('共用时:' + (endTime - startTime) / 1000 + '秒。');
}
}, 500);
function queryData() {
const dataItems = [];
return new Promise(r => {
const fr = fs.createReadStream('/Users/chenfeng/Downloads/buyers.csv', {encoding: 'utf-8'});
const rl = readline.createInterface({
input: fr
});
rl.on('line', line => {
passedLength += line.length;
const splits = line.split(',');
dataItems.push({
productId: +splits[0],
nickName: splits[1],
icon: splits[2],
time: splits[3],
});
});
rl.on('close', () => {
r(dataItems);
});
});
}
const buyereds = {};
async function excute() {
const result = await queryData();
console.log('result: ', result.length)
const dataByUser = {};
const dataByDate = {};
_.forEach(result, (item, index) => {
const userKey = `${item.nickName}${item.icon}`;
const dateKey = dayjs(item.time).format('YYYY-MM-DD');
if (!dataByUser[userKey]) {
dataByUser[userKey] = [item.time];
} else {
dataByUser[userKey].push(item.time);
}
if (dayjs(item.time).diff(dayjs('2018-11-01'), 'day') >= 0) {
if (!dataByDate[dateKey]) {
dataByDate[dateKey] = [userKey];
} else {
dataByDate[dateKey].push(userKey);
}
}
!(index % 10000) && console.log('process:', index)
});
console.log('process over');
const start = dayjs('2018-11-01');
const end = dayjs(Date.now());
const diff = end.diff(start, 'day');
for (let i = 0; i <= diff; i++) {
const date = start.add(i, 'day');
const dateKey = date.format('YYYY-MM-DD');
console.log('calc:', i);
if (dataByDate[dateKey]) {
const allBuyers = dataByDate[dateKey].length;
const oldBuyers = dataByDate[dateKey].filter(key => {
if (buyereds[key]) {
return true;
}
if (dataByUser[key]) {
const isBuy = _.some(dataByUser[key], item => {
return dayjs(item).diff(date, 'day') < 0;
});
if (isBuy) {
buyereds[key] = true;
dataByUser[key].length = 0;
}
return isBuy;
}
return false;
});
dataByDate[dateKey].length = 0;
console.log(`data:${dateKey},${allBuyers - oldBuyers.length},${oldBuyers.length}`);
}
}
}
excute();