-
Notifications
You must be signed in to change notification settings - Fork 2
/
answerUtils.mjs
50 lines (45 loc) · 1.39 KB
/
answerUtils.mjs
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
import toml from 'toml'
import fs from 'fs'
import glob from 'glob'
import path from 'path'
const __dirname = path.resolve()
const allMaterial = glob.sync(path.join(__dirname, '/material/**/*.toml'))
.map(path => fs.readFileSync(path, { encoding: 'utf-8'}))
.map(file => toml.parse(file))
.map(material => {
material.tags = material.tags.replace(/\s/g, '').split(',')
return material
})
/**
* @description Method to get random element from array
* @param {*[]} arr the array
* @returns {*} random element
* @example random(['a', 'b', 'c'])
*/
export const random = arr => {
return arr[Math.floor(Math.random() * arr.length)]
}
export const getMostRelevantAnswer = query => {
if (!query) return null
let answers = allMaterial
.map(material => {
material.hits = query
.split(' ')
.filter(keyword => keyword.indexOf('#') === 0)
.map(keyword => keyword.toLowerCase().replace(/[^a-z0-9]/g, ''))
.filter(keyword => material.tags.indexOf(keyword.toLowerCase()) !== -1)
.length
return material
})
.filter(material => material.hits > 0)
.sort((a, b) => a.hits > b.hits ?
1 :
a.hits < b.hits ?
-1 :
Math.random() < .5 ? 1 : -1
)
let mostRelevantAnswer = answers.pop()
if (!mostRelevantAnswer) return null
let url = random(mostRelevantAnswer.links)
return `${mostRelevantAnswer.answer} ${url}`
}