-
Notifications
You must be signed in to change notification settings - Fork 0
/
quotes.js
57 lines (49 loc) · 1.75 KB
/
quotes.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
const csvFilePath = 'other/quote.csv';
const getRandomInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
const readFile = async (filePath) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(new Error(`Failed to fetch file (status ${xhr.status})`));
}
};
xhr.onerror = () => {
reject(new Error('Failed to fetch file'));
};
xhr.open('GET', filePath);
xhr.send();
});
};
const getLineCount = async (contents) => {
const lines = contents.split('\n');
return lines.length;
};
const getLine = async (contents, lineNumber) => {
const lines = contents.split('\n');
if (lineNumber >= 0 && lineNumber < lines.length) {
return lines[lineNumber];
} else {
throw new Error(`Line number ${lineNumber} not found in file`);
}
};
const processCsv = async () => {
try {
const contents = await readFile(csvFilePath);
const lineCount = await getLineCount(contents);
const randomLineNumber = getRandomInt(0, lineCount - 1);
const line = await getLine(contents, randomLineNumber);
const [quote, name] = line.split(';');
console.log(`Random line number: ${randomLineNumber}`);
console.log(`Variable 1: ${quote}`);
console.log(`Variable 2: ${name}`);
document.getElementById("q1").textContent = quote;
document.getElementById("n1").textContent = name;
} catch (error) {
console.error('Error:', error.message);
}
};