-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkov.js
325 lines (273 loc) · 9.83 KB
/
markov.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// Markov is a simple Markov algorithm (famously known as Normal algorithms) interpreter.
//
// There are 3 components to this library:
//
// 1. Markov.Statement
// 2. Markov.Algorithm
// 3. Markov.Runner
var Markov = {};
// **Markov.Statement**
//
// A Markov.Statement is a string rewriting statement. Generally these are represented as:
// `lhs -> rhs` where the first occurence of `lhs` in the context string gets rewritten as
// `rhs`. This object contains the 'compiled' form of the statement, and can handle any
// form.
//
// **Note:** The *empty word* or *empty string* is represented by `!`.
Markov.Statement = (function() {
// Markov.Statement Constructor
//
// `from` - the L.H.S. of the rewrite rule
// `to` - the R.H.S. of the rewrite rule
// `closing` - boolean whether this is a closing (terminating) statement
var Statement = function(from, to, closing) {
this.setFrom(from);
this.setTo(to);
this.closing = closing;
}
;
// This is the regular expression that `Markov.Statement.compile()` uses to compile rewrite
// rules into a Markov.Statement.
//
Statement.REGEX = /\s*(\S*)\s*[=-]\s*>\s*(\.)*\s*(\S*)\s*/i;
// Compiles a rewrite statement in the form of:
//
// lhs ->. rhs
//
// *or*
//
// lhs =>. rhs
//
// Wehere a `.` at the end signifies a closing rewrite rule (terminates the algorithm).
// There can be any amount of whitespace between any part, except for in the `lhs` and `rhs`.
//
// For example, the following is **not** a valid statement:
//
// in valid -> statement
//
Statement.compile = function(statement) {
var compiled = Statement.REGEX.exec(statement);
if (!compiled) {
throw new Error('Invalid statement: ' + statement);
}
if (compiled[1].length < 1) {
throw new Error('Invalid statement, there is no LHS: ' + statement);
}
if (compiled[3].length < 1) {
throw new Error('Invalid statement, there is no RHS: ' + statement);
}
if (compiled[1] === "!!") {
throw new Error('Invalid statement, LHS contains two empty word denominators: ' + statement);
}
if (compiled[3] === "!!") {
throw new Error('Invalid statement, RHS contains two empty word denominators: ' + statement);
}
return new Statement(compiled[1],compiled[3],!!compiled[2]);
}
;
// Sets the `from` property of the Markov.Statement object.
//
Statement.prototype.setFrom = function(from) {
this.from = from;
}
;
// Sets the `to` property of the Markov.Statement object.
//
// **Note:** The `to` property does not contain the empty string character. It automatically
// gets cleaned up to its functional representation.
//
Statement.prototype.setTo = function(to) {
var clean = to.replace('!', '').replace('!', '');
this.to = clean;
}
;
Statement.prototype.toString = function() {
var statement = (this.from.length < 1 ? '!' : this.from);
statement += (this.closing ? ' ->. ' : ' -> ');
statement += (this.to.length < 1 ? '!' : this.to);
return statement;
}
;
return Statement;
}
).call();
// **Markov.Algorithm**
//
// A Markov.Algorithm is an ordered collection of at least one Markov.Statement.
//
Markov.Algorithm = (function() {
var Algorithm = function() {
this.statements = [];
}
;
// Returns `true` if this Markov.Algorithm has any statements in it.
//
Algorithm.prototype.hasStatements = function() {
return this.statements.length > 0;
}
;
// Returns a copy of the statements inside this Markov.Algorithm.
//
Algorithm.prototype.getStatements = function() {
return Array.apply([], this.statements);
}
;
// Gets a statement at a specified position inside this Markov.Algorithm.
//
Algorithm.prototype.getStatement = function(position) {
return this.statements[position];
}
;
// Sets a statement at a specified position inside this Markov.Algorithm.
// It's not wise to change a statement when a Markov.Algorithm is running inside
// a Markov.Runner.
//
Algorithm.prototype.setStatement = function(statement, position) {
if (!(statement instanceof Markov.Statement)) {
throw new Error('Statement must be an instance of Markov.Statement.');
}
var previous = this.statements[position];
this.statements[position] = statement;
return previous;
}
;
// Adds a statement at the beginning, end or anywhere in between.
//
// `statement` - the statement to add
// `position` - the position where to add the statement
// if less than 0 puts it at the top of the algorithm
// if greather than the number of statements or omitted, puts it at the end
//
Algorithm.prototype.addStatement = function(statement, position) {
if (!(statement instanceof Markov.Statement)) {
throw new Error('Statement must be an instance of Markov.Statement.');
}
if (typeof position === 'undefined' || typeof position === 'null' || statement < 0 || statement > this.statements.length) {
this.statements.push(statement);
} else {
this.statements = this.statements.slice(0, position).concat(statement).concat(this.statements.slice(position));
}
return this;
}
;
// Removes a statement from a specified position. See #addStatement() for the conventions.
Algorithm.prototype.removeStatement = function(position) {
if (typeof position === 'undefined' || typeof position === 'null' || position >= this.statements.length - 1) {
return this.statements.pop();
} else if (position < 0) {
return this.statements.shift();
}
var statement = this.statements[position];
this.statements = this.statements.slice(0, position).concat(this.statements.slice(0, position + 1));
return statement;
}
;
return Algorithm;
}
).call();
// **Markov.Runner**
//
// Markov.Runner is runs a Markov.Algorithm over a certain string context.
Markov.Runner = (function() {
// Markov.Runner Constructor
//
// Constructs a new Markov.Runner object. Markov.Runner objects are meant to be for
// one-time use, meaning you should create a new runner every single time you wish
// to run a Markov.Algorithm.
//
// `algorithm` - the Markov.Algorithm to be executed
// `context` - a string representing the context
//
// *Properties*:
//
// `context` - the current executing context
// `algorithm` - the Markov.Algorithm to be executed
// `steps` - an array of `{ context: ..., statement: ... }` containing all of the steps
// `done` - boolean whether the execution has finished
//
var Runner = function(algorithm, context) {
if (!algorithm || !(algorithm instanceof Markov.Algorithm)) {
throw new Error('Markov.Runner requires a non-null Markov.Algorithm to run.');
}
if (typeof context !== 'string') {
throw new Error('Markov.Runner requires a non-null String context.');
}
this.context = context;
this.algorithm = algorithm;
this.steps = [];
this.done = false;
}
;
// Runs the current Markov.Algorithm over the string context.
//
// After calling this, it return `false` or `true`
//
// ToDo/Bug: No check for endless loop.
Runner.prototype.run = function(interval) {
if (this.done) {
return false;
}
while (!done) {
this.step();
}
return true;
}
;
// Stops the Markov.Runner, after this the runner can't be re-started.
//
Runner.prototype.stop = function() {
this.done = true;
}
;
// Steps through the execution of the Markov.Algorithm.
// Expect error returns: `infinity` if cycle never ends.
//
// Returns the Markov.Statement from the algorithm that was chosen, or `null` if none was
// applicable (natural termination).
//
Runner.prototype.step = function() {
if (this.done) {
return null ;
}
if (this.steps.length < 1) {
this.steps.push({
context: this.context,
statement: null
});
}
var statements = this.algorithm.getStatements()
,
i = 0
,
acted = false
,
statement = null ;
for (i = 0; i < statements.length; i++) {
statement = statements[i];
var to = statement.to
,
from = statement.from;
if (this.context.search(statement.from) > -1) {
this.context = this.context.replace(statement.from, statement.to);
} else {
continue;
}
this.steps.push({
context: this.context,
statement: statement
});
acted = true;
break;
}
if ((this.steps.length - 2 > -1) && this.context === this.steps[this.steps.length - 2].context) {
throw new Error("Endless cycle detected")
}
if (!acted || statement.closing) {
this.stop();
}
return acted ? statement : null ;
}
;
return Runner;
}
).call();