-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.js
93 lines (79 loc) · 2.47 KB
/
generator.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
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// generator.js
// written and released to the public domain by drow <[email protected]>
// http://creativecommons.org/publicdomain/zero/1.0/
var gen_data = {};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// generator function
function generate_text (type) {
var list; if (list = gen_data[type]) {
var string; if (string = select_from(list)) {
return expand_tokens(string);
}
}
return '';
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// generate multiple
function generate_list (type, n_of) {
var list = [];
var i; for (i = 0; i < n_of; i++) {
list.push(generate_text(type));
}
return list;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// select from list
function select_from (list) {
if (list.constructor == Array) {
return select_from_array(list);
} else {
return select_from_table(list);
}
}
function select_from_array (list) {
return list[Math.floor(Math.random() * list.length)];
}
function select_from_table (list) {
var len; if (len = scale_table(list)) {
var idx = Math.floor(Math.random() * len) + 1;
var key; for (key in list) {
var r = key_range(key);
if (idx >= r[0] && idx <= r[1]) { return list[key]; }
}
}
return '';
}
function scale_table (list) {
var len = 0;
var key; for (key in list) {
var r = key_range(key);
if (r[1] > len) { len = r[1]; }
}
return len;
}
function key_range (key) {
var match; if (match = /(\d+)-00/.exec(key)) {
return [ parseInt(match[1]), 100 ];
} else if (match = /(\d+)-(\d+)/.exec(key)) {
return [ parseInt(match[1]), parseInt(match[2]) ];
} else if (key == '00') {
return [ 100, 100 ];
} else {
return [ parseInt(key), parseInt(key) ];
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// expand {token} in string
function expand_tokens (string) {
var match; while (match = /{(\w+)}/.exec(string)) {
var token = match[1];
var repl; if (repl = generate_text(token)) {
string = string.replace('{'+token+'}',repl);
} else {
string = string.replace('{'+token+'}',token);
}
}
return string;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -