-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfake-data-generator.html
More file actions
227 lines (211 loc) · 9.56 KB
/
fake-data-generator.html
File metadata and controls
227 lines (211 loc) · 9.56 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fake data generator</title>
<link rel="stylesheet" href="styles-vanilla.css" />
</head>
<body>
<div class="card">
<h2>Fake Data Generator</h2>
<p class="subtle">Define a schema one field per line using the format <span class="pill">name:type</span>. Then generate mock rows as JSON, CSV, or SQL inserts.</p>
<div class="field">
<label for="schema-input">Schema</label>
<textarea id="schema-input" placeholder="Example:
id:number
name:fullName
email:email
created_at:date
is_active:boolean"></textarea>
</div>
<div class="row-3">
<div class="field">
<label for="row-count">Rows</label>
<input id="row-count" type="number" min="1" max="500" value="10" />
</div>
<div class="field">
<label for="data-format">Output format</label>
<select id="data-format">
<option value="json" selected>JSON</option>
<option value="csv">CSV</option>
<option value="sql">SQL inserts</option>
</select>
</div>
<div class="field">
<label for="table-name">Table name</label>
<input id="table-name" type="text" placeholder="users" value="users" />
</div>
</div>
<div class="muted-box">
Supported types: number, integer, fullName, firstName, lastName, email, phone, company, city, country, username, boolean, uuid, slug, sentence, paragraph, date, timestamp, price.
</div>
<div class="actions">
<button class="primary" id="generate-data-btn">Generate fake data</button>
<button class="secondary" id="copy-data-btn">Copy output</button>
<button class="secondary" id="download-data-btn">Download file</button>
<button class="secondary" id="sample-data-btn">Load sample</button>
</div>
</div>
</div>
<div class="stack">
<div class="card">
<h3>Output</h3>
<div id="data-output" class="output">Generated data will appear here.</div>
</div>
<script>
// Fake data generator
const fakeData = {
firstNames: ['Mona', 'Ashly', 'Riley', 'Jordan', 'Avery', 'Taylor', 'Morgan', 'Dakota', 'Robin', 'Sydney'],
lastNames: ['Lorenzana', 'Reed', 'Williams', 'Nguyen', 'Garcia', 'Bennett', 'Miller', 'Santos', 'Chen', 'Brooks'],
cities: ['Portland', 'Seattle', 'Austin', 'Chicago', 'Miami', 'Denver', 'Phoenix', 'Boston', 'Atlanta', 'Oakland'],
countries: ['United States', 'Canada', 'Mexico', 'France', 'Japan', 'Germany', 'Brazil', 'Spain', 'Australia', 'Netherlands'],
companies: ['Northline Studio', 'Pixel Harbor', 'Signal Forge', 'Quiet Orbit', 'Velvet Grid', 'Paper Lantern', 'Open Meadow', 'Bright Relay'],
words: ['aurora', 'signal', 'paper', 'frontend', 'widget', 'archive', 'garden', 'ember', 'delta', 'violet', 'harbor', 'lumen']
};
function rand(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
function randInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
function randBool() { return Math.random() > 0.5; }
function randDigits(n) { return Array.from({ length: n }, () => randInt(0, 9)).join(''); }
function randWord(count = 1) { return Array.from({ length: count }, () => rand(fakeData.words)).join(' '); }
function randSentence() {
const len = randInt(5, 11);
const sentence = Array.from({ length: len }, () => rand(fakeData.words)).join(' ');
return titleCase(sentence) + '.';
}
function randParagraph() {
return Array.from({ length: randInt(2, 4) }, () => randSentence()).join(' ');
}
function makeUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function generateFieldValue(type, index) {
const first = rand(fakeData.firstNames);
const last = rand(fakeData.lastNames);
switch ((type || '').trim()) {
case 'number':
case 'integer': return randInt(1, 9999);
case 'fullname':
case 'fullName': return `${first} ${last}`;
case 'firstname':
case 'firstName': return first;
case 'lastname':
case 'lastName': return last;
case 'email': return `${first.toLowerCase()}.${last.toLowerCase()}${randInt(1, 99)}@example.com`;
case 'phone': return `(${randInt(200, 989)}) ${randInt(100, 999)}-${randInt(1000, 9999)}`;
case 'company': return rand(fakeData.companies);
case 'city': return rand(fakeData.cities);
case 'country': return rand(fakeData.countries);
case 'username': return `${first.toLowerCase()}_${last.toLowerCase()}${randInt(10, 999)}`;
case 'boolean': return randBool();
case 'uuid': return makeUUID();
case 'slug': return slugify(randWord(randInt(2, 4)) + ' ' + index);
case 'sentence': return randSentence();
case 'paragraph': return randParagraph();
case 'date': {
const date = new Date(Date.now() - randInt(0, 365) * 86400000);
return date.toISOString().slice(0, 10);
}
case 'timestamp': {
const date = new Date(Date.now() - randInt(0, 365) * 86400000 - randInt(0, 86400000));
return date.toISOString();
}
case 'price': return (Math.random() * 300 + 5).toFixed(2);
default: return randSentence();
}
}
function parseSchema() {
const raw = $('#schema-input').value.trim();
const lines = raw.split(/\n+/).map((line) => line.trim()).filter(Boolean);
const schema = lines.map((line) => {
const [name, type] = line.split(':').map((part) => part.trim());
return { name, type };
}).filter((item) => item.name && item.type);
const tbody = $('#schema-table tbody');
if (!schema.length) {
tbody.innerHTML = '<tr><td colspan="2" class="small">No valid schema parsed yet.</td></tr>';
} else {
tbody.innerHTML = schema.map((field) => `<tr><td>${field.name}</td><td>${field.type}</td></tr>`).join('');
}
return schema;
}
$('#schema-input').addEventListener('input', parseSchema);
function generateFakeData() {
const schema = parseSchema();
const count = Math.max(1, Math.min(500, parseInt($('#row-count').value || '10', 10)));
const format = $('#data-format').value;
const tableName = ($('#table-name').value || 'users').trim();
if (!schema.length) {
$('#data-output').textContent = 'Please define a valid schema first.';
return;
}
const rows = Array.from({ length: count }, (_, index) => {
const obj = {};
schema.forEach((field) => {
obj[field.name] = generateFieldValue(field.type, index + 1);
});
return obj;
});
let output = '';
if (format === 'json') {
output = JSON.stringify(rows, null, 2);
} else if (format === 'csv') {
const headers = schema.map((f) => f.name);
const csvLines = [headers.join(',')];
rows.forEach((row) => {
csvLines.push(headers.map((key) => {
const value = row[key];
const str = String(value).replace(/"/g, '""');
return /[",\n]/.test(str) ? `"${str}"` : str;
}).join(','));
});
output = csvLines.join('\n');
} else if (format === 'sql') {
const cols = schema.map((f) => f.name).join(', ');
const statements = rows.map((row) => {
const values = schema.map((field) => {
const value = row[field.name];
if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE';
if (typeof value === 'number') return String(value);
return `'${String(value).replace(/'/g, "''")}'`;
}).join(', ');
return `INSERT INTO ${tableName} (${cols}) VALUES (${values});`;
});
output = statements.join('\n');
}
$('#data-output').textContent = output;
}
function downloadFakeData() {
const output = $('#data-output').textContent;
if (!output || output.includes('Generated data will appear here') || output.includes('Please define')) {
alert('Generate some data first.');
return;
}
const format = $('#data-format').value;
const ext = format === 'sql' ? 'sql' : format;
const blob = new Blob([output], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `fake-data.${ext}`;
a.click();
URL.revokeObjectURL(url);
}
$('#generate-data-btn').addEventListener('click', generateFakeData);
$('#copy-data-btn').addEventListener('click', () => copyText($('#data-output').textContent));
$('#download-data-btn').addEventListener('click', downloadFakeData);
$('#sample-data-btn').addEventListener('click', () => {
$('#schema-input').value = 'id:number\nname:fullName\nemail:email\ncity:city\ncompany:company\ncreated_at:timestamp\nis_active:boolean\nprice:price';
$('#row-count').value = '10';
$('#data-format').value = 'json';
$('#table-name').value = 'users';
parseSchema();
generateFakeData();
});
</script>
</body>
</html>