Repository navigation
Expand file tree
/
Copy pathgenerator.js
More file actions
87 lines (69 loc) · 2.47 KB
/
Copy pathgenerator.js
File metadata and controls
87 lines (69 loc) · 2.47 KB
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
function pick(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function pickExcluding(arr, exclude) {
const filtered = arr.filter(item => !exclude.has(item));
if (filtered.length === 0) return pick(arr);
return pick(filtered);
}
function expand(str) {
let result = str;
const seen = {}; // track picks per token key to avoid dupes
for (let i = 0; i < 10; i++) { // prevents infinite loops
// optional tokens: {?KEY} → 50% chance to appear, 50% gone
result = result.replace(/\{\?(\w+)\}/g, (_, key) => {
if (Math.random() < 0.5) return "";
const pool = TOKENS[key];
if (!pool) return "";
if (!seen[key]) seen[key] = new Set();
const value = pickExcluding(pool, seen[key]);
seen[key].add(value);
return value;
});
// required tokens: {KEY}
result = result.replace(/\{(\w+)\}/g, (_, key) => {
const pool = TOKENS[key];
if (!pool) return "";
if (!seen[key]) seen[key] = new Set();
const value = pickExcluding(pool, seen[key]);
seen[key].add(value);
return value;
});
if (!result.match(/\{.*?\}/)) break;
}
return result;
}
// history dedup: remember recent templates to avoid repetition
const recentTemplates = [];
const HISTORY_SIZE = 5;
function pickTemplate() {
// try a few times to avoid recently used templates
for (let attempt = 0; attempt < 10; attempt++) {
const idx = Math.floor(Math.random() * TEMPLATES.length);
if (!recentTemplates.includes(idx) || attempt === 9) {
recentTemplates.push(idx);
if (recentTemplates.length > HISTORY_SIZE) recentTemplates.shift();
return TEMPLATES[idx];
}
}
return pick(TEMPLATES);
}
function generateHeadline() {
const template = pickTemplate();
let headline = expand(template);
headline = headline
.replace(/\s+/g, " ")
.replace(/\s+([?.!,])/g, "$1")
.replace(/^,\s*/, "")
.trim();
// only add random ending punctuation if it doesn't already end with some
if (!/[.!?]$/.test(headline)) {
headline += pick([".", ".", "", "", "??"]);
}
return headline.replace(/^./, c => c.toUpperCase());
}
function render() {
document.getElementById("headline").textContent = generateHeadline();
}
document.getElementById("refresh").addEventListener("click", render);
render();