-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
94 lines (85 loc) · 2.25 KB
/
index.js
File metadata and controls
94 lines (85 loc) · 2.25 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
const http = require('http')
const url = require('url')
function extractRow(array) {
const found = array.find((el) => {
return el.startsWith("row:")
})
const res = found === undefined ? -1 : Math.abs(parseInt(found.split(":")[1]))
return res !== 0 ? res : -1
}
function extractColumn(array) {
const found = array.find((el) => {
return el.startsWith("column:")
});
const res = found === undefined ? 1 : Math.abs(parseInt(found.split(":")[1]))
return res !== 0 ? res : 1
}
function extractArgs(array) {
return array.filter((el) => {
return !el.startsWith("row:") && !el.startsWith("column:")
})
}
// Fisher-Yates Shuffle
function shuffle(array) {
let n = array.length, t, i;
while (n) {
i = Math.floor(Math.random() * n--);
t = array[n];
array[n] = array[i];
array[i] = t;
}
return array;
}
function chunk(array, size) {
const len = array.length
let res = [],
start = 0,
end = 0
while(end !== len) {
end = start + size
if (end > len) {
end = len
}
res.push(array.slice(start, end))
start = end
}
return res
}
function makeResponseText(row, column, candidates) {
const chunked = chunk(candidates, column)
const sliced = chunked.slice(0, (row === -1 ? chunked.length : row))
const maped = sliced.map((el, idx) => {
return `${idx+1}: ` + el.join(", ")
})
return maped.join("\n")
}
const server = http.createServer((req, res) => {
const text = url.parse(req.url, true).query.text
if (text === undefined || text.length === 0) {
res.setHeader("content-type", "application/json")
res.end(JSON.stringify({
"response_type": "ephemeral",
"text": "Please set a text"
}))
return
}
const texts = text.split(/\s+/)
const row = extractRow(texts)
const column = extractColumn(texts)
const args = extractArgs(texts)
if (args.length === 0) {
res.setHeader("content-type", "application/json")
res.end(JSON.stringify({
"response_type": "ephemeral",
"text": "Please set candidates"
}))
return
}
const candidates = shuffle(args)
res.setHeader("content-type", "application/json")
res.end(JSON.stringify({
"response_type": "in_channel",
"text": makeResponseText(row, column, candidates)
}));
})
server.listen(8000)