This repository has been archived by the owner on Sep 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (53 loc) · 1.66 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
// initialize modules
var hn_analyzer = module.exports = {}
// external dependencies
var HN = require('hnindex')
var natural = require('natural')
var fs = require('fs')
// local dependencies
var train = require('./trainer.js')
// load templates
var templates = {
main: fs.readFileSync('templates/main.html').toString(),
result: fs.readFileSync('templates/result.html').toString(),
ranking: fs.readFileSync('templates/ranking.html').toString(),
}
// instantiate classifier and train
var classifier = new natural.BayesClassifier()
train(classifier)
// render the results page
hn_analyzer.render = function(cb) {
// initiate request to HN
HN.popular( function(err, results) {
// construct rankedResults array
results.entries.forEach(function(entry) {
entry.rankings = classifier.getClassifications(entry.title)
})
var output = renderPage(results.entries)
cb(output)
})
}
// rendering logic
function renderPage(entries) {
return templates.main.replace('{{body}}',renderResults(entries))
}
function renderResults(entries) {
return entries.map(function(entry) {
return templates.result
// article title
.replace('{{title}}',entry.title)
// article url
.replace('{{url}}',entry.url)
// ranking partial
.replace('{{rankings}}',renderRankings(entry.rankings))
}).join(' ')
}
function renderRankings(rankings) {
return rankings.sort().slice(0,3).map(function(ranking) {
return templates.ranking
// the ranking title
.replace('{{label}}',ranking.label)
// the confidence percentage with 2 decimal points
.replace('{{value}}',Math.floor(ranking.value * 100 * 100)/100 + '%')
}).join(' ')
}