This repository has been archived by the owner on Sep 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
186 lines (165 loc) · 4.75 KB
/
index.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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import chalk from 'chalk';
import imageToAscii from "image-to-ascii";
import fs, {promises} from 'fs';
import _ from 'lodash';
import csv from 'csv-parser';
const primary = chalk.hex('#1A6DFF')
function maskingName(strName) {
if (strName.length > 2) {
var originName = strName.split('');
originName.forEach(function(name, i) {
if (i === 0 || i === originName.length - 1) return;
originName[i] = '*';
});
var joinName = originName.join();
return joinName.replace(/,/g, '');
} else {
var pattern = /.$/; // 정규식
return strName.replace(pattern, '*');
}
};
function maskingPhone(pn) {
const regex = /\d(?=\d{4})/mg;
return pn.replace(regex, "*");
}
function maskingEmail(email) {
email = email.split('');
let finalArr=[];
let len = email.indexOf('@');
email.forEach((item,pos)=>{
(pos>=1 && pos<=len-2) ? finalArr.push('*') : finalArr.push(email[pos]);
})
return finalArr.join('')
}
/**
* 중복참여 방지
* 동명이인이 있을 수 있음으로 이메일로만 체크
* @param Array data
* @returns set
*/
export function duplicatedCheck(data) {
// 중복 제거 기준 이름 확인 > 이메일
return _.uniqBy(data, function (e) {
return e['이메일'];
});
}
/**
* 특정 숫자 제외 랜덤 숫자
*/
function generateRandom(min, max, exclude) {
let random;
while (!random) {
const x = Math.floor(Math.random() * (max - min + 1)) + min;
if (exclude.indexOf(x) === -1) random = x;
}
return random;
}
export function getFileContentsCsv(fileName){
const results = [];
const stream = fs.createReadStream(fileName)
.pipe(csv())
.on('data', (data) => results.push(data))
// .on('end', () => {
// console.log(results);
// });
;
return new Promise((resolve, reject) => {
stream.on('error', function(err){
// console.log('File read Error.');
resolve(reject);
})
stream.on('end', function(){ // nodejs에서 Stream은 기본적으로 event emitter이다.
// console.log('ReadStream End.');
resolve(results); // Array 반환
})
})
}
// core 'library' exposing native node console capabilities for co-routines
function getAnswer() {
process.stdin.resume();
return new Promise((resolve) => {
process.stdin.once("data", function (data) {
resolve(data.toString().trim());
});
});
}
async function runSequence(sequenceFactory, clearScreen = false, etcLog) {
function print(msg, end = "\n") {
process.stdin.write(msg + end);
}
let answer = undefined;
const sequence = sequenceFactory(print);
while (true) {
const { value: question } = await sequence.next(answer);
if (question) {
print(question, " : ");
answer = await getAnswer();
if (clearScreen) {
console.clear();
etcLog && console.log(etcLog);
}
} else {
break;
}
}
}
async function* createOriginalPostersSequence(print) {
console.log(primary("\nJSConf imweb에 오신것을 환경합니다.\n"))
let ready = "";
while (!ready) {
ready = yield "참여자 추첨 [Y/n]";
// 기본값 처리
if (!ready) {
ready = 'Y';
}
if (ready == 'n' || ready == 'N') {
process.exit(0);
}
}
print('🎉 축 당첨\n');
let data = await getFileContentsCsv('data.csv');
data = duplicatedCheck(data);
let results = [];
while(results.length < 5) {
const is = yield 'enter: ';
print('🎉 축 당첨\n');
const randomIndex = generateRandom(0,data.length - 1, results.map(e => e.key));
const chosen = data[randomIndex];
chosen['key'] = randomIndex;
results.push(chosen);
results.map((e, index) => {
let unit = primary('2등: ');
if (index == 4) {
unit = chalk.hex('#00D69A')('1등: ')
}
const r = unit + `${maskingName(e['성함'])} ${maskingEmail(e['이메일'])} ${maskingPhone(e['연락처'])}`;
print(r);
})
}
print(`\nJSConf 2022 아임웹 부스에 참여해주셔서 감사합니다.\n\n\n\n\n\n\n\n\n`);
await promises.writeFile('result.txt', results.map(e => `${e['성함']} ${e['이메일']} ${e['연락처']}`).join('\n'), err => {
console.log(err);
});
}
// 파일유무 확인
export const fileExists = async path => !!(await promises.stat(path).catch(e => false));
async function run(logo) {
console.clear();
console.log(logo);
const exists = await fileExists('./result.txt');
if (exists) {
console.log('이미 추첨이 완료되었습니다. 감사합니다 🙏')
process.exit(0)
};
await runSequence(createOriginalPostersSequence, true, logo);
process.exit(0);
}
imageToAscii('https://vendor-cdn.imweb.me/images/main/imweb-favicon-192x192.png?v1', {
white_bg: false,
size: {
width: 20,
height: 20
}
}, (err, converted) => {
run(converted)
});