-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.js
67 lines (55 loc) · 1.46 KB
/
generate.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
var _ = require('lodash')
var fs = require('fs')
var quotes = JSON.parse(fs.readFileSync('quotes.json'))
function prefix (len) {
this.len = len
this.terms = []
}
prefix.prototype.pushTerm = function (term) {
this.terms.push(term)
if (this.terms.length > this.len) {
this.terms.shift()
}
}
prefix.prototype.toString = function () {
return this.terms.join(' ')
}
function buildChain (quotes, pfxLen) {
var chain = {
chain: {},
len: pfxLen,
authors: [],
}
_.each(quotes, function (q) {
chain.authors.push(q.author)
var pfx = new prefix(chain.len)
_.each(q.quote.split(' '), function (word) {
if (!chain.chain[pfx.toString()]) {
chain.chain[pfx.toString()] = []
}
chain.chain[pfx.toString()].push(word)
pfx.pushTerm(word)
})
})
return chain
}
function generateSentence (chain) {
var words = []
var pfx = new prefix(chain.len)
var choices
while (choices = chain.chain[pfx.toString()]) {
words.push(_.sample(choices))
pfx.pushTerm(_.last(words))
}
return words.join(' ')
}
function generateQuote (chain) {
var s
while (!s || _.any(quotes, function (q) {
return q.quote === s
})) {
s = generateSentence(chain)
}
return '"' + s + '" - ' + _.chain(chain.authors).unique().sample().value()
}
console.log(generateQuote(buildChain(quotes, 2)))