-
Notifications
You must be signed in to change notification settings - Fork 17
/
mod.ts
123 lines (106 loc) · 2.57 KB
/
mod.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
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
// mod.ts
import { phrases, sentenceTemplates } from "./utils/sample.ts";
import {
generator,
pickLastPunc,
rand,
randfloat,
randint,
} from "./utils/helper.ts";
export { generate as lorem } from "./utils/lorem.ts";
export {
addAdjectives,
addNouns,
addTemplates,
getAdjectives,
getNouns,
getTemplates,
setAdjectives,
setNouns,
setTemplates,
} from "./utils/sample.ts";
const actions: string[] = [
"noun",
"a_noun",
"nouns",
"adjective",
"an_adjective",
];
const trim = (s: string): string => {
return s.replace(/^[\s\xa0]+|[\s\xa0]+$/g, "")
.replace(/\r?\n|\r/g, " ")
.replace(/\s\s+|\r/g, " ");
};
const runGenerator = (action: string) => {
return generator[action as keyof typeof generator]();
};
const make = (template: string): string => {
let sentence = String(template);
const occurrences = template.match(/\{\{(.+?)\}\}/g);
if (occurrences && occurrences.length) {
for (let i = 0; i < occurrences.length; i++) {
const action = trim(occurrences[i].replace("{{", "").replace("}}", ""));
const result = actions.includes(action) ? runGenerator(action) : "";
sentence = sentence.replace(occurrences[i], result);
}
}
return sentence;
};
const randomStartingPhrase = (): string => {
if (randfloat() < 0.33) {
return rand(phrases);
}
return "";
};
const makeSentenceFromTemplate = (): string => {
return make(rand(sentenceTemplates));
};
/**
* Generate a sentence with or without starting phrase
*
* @param ignoreStartingPhrase. Set to true to add a short phrase at the begining
* @returns A sentence
*/
export const sentence = (ignoreStartingPhrase: boolean = false): string => {
const phrase = ignoreStartingPhrase ? "" : randomStartingPhrase();
let s = phrase + makeSentenceFromTemplate();
s = s.charAt(0).toUpperCase() + s.slice(1);
s += pickLastPunc();
return s;
};
/**
* Generate a paragraph with given sentence count
*
* @param len Sentence count, 3 to 15
* @returns A paragraph
*/
export const paragraph = (len: number = 0): string => {
if (!len) {
len = randint(3, 10);
}
const t = Math.min(len, 15);
const a = [];
while (a.length < t) {
const s = sentence();
a.push(s);
}
return a.join(" ");
};
/**
* Generate an article with given paragraph count
*
* @param len Paragraph count, 3 to 15
* @returns An article
*/
export const article = (len: number = 0): string => {
if (!len) {
len = randint(3, 10);
}
const t = Math.min(len, 15);
const a = [];
while (a.length < t) {
const s = paragraph();
a.push(s);
}
return a.join("\n\n");
};