-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenerateMessage.ts
78 lines (61 loc) · 1.97 KB
/
GenerateMessage.ts
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
import ProcessTalkHistory from "./ProcessTalkHistory";
// import {data} from "./data"; // DEBUG:
// TODO: fix redundant type
type WordChain = {
[key: string]: {
[key2: string]: {
[key3: string]: number
}
}
} | {
[key2: string]: {
[key3: string]: number
}
}
;
class GenerateMessage extends ProcessTalkHistory {
constructor(talkData: string) {
super(talkData);
// super(filename, data); // DEBUG:
}
// TODO: fix type any
wordChoise(dict: any) {
const idx = Math.floor(Math.random() * Object.keys(dict).length);
const key = Object.keys(dict)[idx];
return key;
}
generateBase(dict?: WordChain) {
let success = false; // flag
let wordOutList: Array<string> = [];
while (!success && dict) { // avoid error
try {
const fst = dict["@"]; // @ as beginning of sentence
let w1 = this.wordChoise(fst);
let w2 = this.wordChoise(fst[w1]);
wordOutList.push(w1);
wordOutList.push(w2);
while (true){
const w3 = this.wordChoise(dict[w1][w2]);
wordOutList.push(w3);
if (w3 === "^"){ // if end of sentence
success = true;
break;
}
w1 = w2;
w2 = w3;
}
}catch(err){
console.log("err: ", err);
}
}
const wordOut = wordOutList.join("");
return wordOut.slice(0, wordOut.indexOf("^")); // return words til ^ got found
}
getGeneratedMessage(sender: string): string {
if (sender === this.opponentName)
return this.generateBase(this.opponentMarkovChain);
else
return this.generateBase(this.myMarkovChain);
}
}
export default GenerateMessage;