-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypingAnalysis.ts
464 lines (428 loc) · 11.3 KB
/
typingAnalysis.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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
interface CharStats {
totalTyped: number;
totalCorrect: number;
timestamps: number[];
}
const sentences = [
"Type this sentence.",
// "Type another sentence.",
// "Here is a third sentence.",
// "And a fourth one.",
// "Finally, a fifth sentence.",
// "Type this sentence. It's a fairly common one!",
// "Here's another sentence, meant to include other characters.",
// "This one has a question mark? And a couple of exclamation points!!",
// "Let's not forget about the number sign # and the dollar sign $.",
// "What about these symbols: ^ & * ( ) _ +",
// "And these ones too: < > ? @ # ~ `",
// "Use the left and right square brackets: [ ]",
// "Here's a sentence with a semi-colon; and a colon: as well.",
// "The quote ' and the double quote \" should not be forgotten.",
// "This one includes a dash - and an underscore _",
// "An uppercase sentence: THIS IS ALL CAPS.",
// "Let's mix upper and lower case: This Is Mixed Case.",
// "Include some numbers: 1234567890.",
// "Finally, a sentence that includes all alphabets: The quick brown fox jumps over the lazy dog.",
// "And one more with all alphabets (in caps): THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.",
];
let currentSentenceIndex = 0;
let currentSentence = sentences[currentSentenceIndex];
const inputElement: HTMLInputElement = document.getElementById(
"input"
) as HTMLInputElement;
const sentenceDiv: HTMLElement = document.getElementById("sentence")!;
sentenceDiv.textContent = currentSentence;
let prevTimestamp = -1;
let charStats: Record<string, CharStats> = {};
let missedKeys: Record<string, number> = {};
let missedKeyPairs: Record<string, number> = {};
let mistakeKeys: Record<string, number> = {};
let mistakeKeyPairs: Record<string, number> = {};
const lowercaseWords = [
"fn",
"let",
"mod",
"struct",
"impl",
"enum",
"match",
"use",
"pub",
"crate",
"trait",
"self",
"super",
"type",
"as",
"if",
"while",
"loop",
"for",
"in",
"return",
"break",
"continue",
"unsafe",
"mut",
"ref",
"Box",
"Option",
"Result",
"Vec",
"String",
"i32",
"u32",
"bool",
"f32",
"f64",
"dyn",
"static",
"drop",
"Default",
"Debug",
"Clone",
"Copy",
"Sized",
"PartialEq",
"Eq",
"PartialOrd",
"Ord",
"ToString",
"From",
"Into",
"AsRef",
"AsMut",
"Borrow",
"BorrowMut",
"ToOwned",
"Deref",
"DerefMut",
"Iterator",
"Fn",
"FnMut",
"FnOnce",
"Future",
"Send",
"Sync",
"'static",
"lifetime",
"async",
"await",
"try",
"map",
"filter",
"unwrap",
"unwrap_or",
"expect",
"panic",
"print",
"println",
"format",
"macro",
"extern",
"const",
"true",
"false",
"Some",
"None",
"Ok",
"Err",
"main",
"test",
"cfg",
"derive",
"where",
"Default",
"std",
"collections",
"HashMap",
"HashSet",
"LinkedList",
"BinaryHeap",
"Rc",
"Arc",
"Mutex",
"RwLock",
"Condvar",
"once",
"thread",
"spawn",
"join",
"catch",
"move",
"and_then",
"or_else",
"unwrap_or_else",
"unwrap_or_default",
"is_err",
"is_ok",
"from_str",
"to_string",
"parse",
"push",
"pop",
"get",
"set",
"insert",
"remove",
"contains",
"len",
"capacity",
"clear",
"new",
"from",
"to",
"as",
"as_mut",
"as_ref",
"clone",
"copy",
"read",
"write",
"open",
"close",
"seek",
"lock",
"try_lock",
"raw",
"bind",
"accept",
"connect",
"listen",
"send",
"recv",
"stream",
"tcp",
"udp",
"io",
"fs",
"net",
"path",
"os",
"env",
"time",
"thread",
"process",
"sync",
"ffi",
"panic",
"hash",
"num",
"str",
"char",
"slice",
"option",
"result",
"fmt",
"alloc",
"cmp",
"iter",
"mem",
];
const punctuationMarks = [";", ",", ":", ".", "!", "?", "->", "=>"];
function generateRandomSentence(): string {
let sentence: string[] = [];
for (let i = 0; i < 20; i++) {
let word =
lowercaseWords[Math.floor(Math.random() * lowercaseWords.length)];
const capitalizeFirstLetter = Math.random() < 0.5;
const capitalizeWholeWord = Math.random() < 0.1;
if (capitalizeWholeWord) {
word = word.toUpperCase();
} else if (capitalizeFirstLetter) {
word = word.charAt(0).toUpperCase() + word.slice(1);
}
sentence.push(word);
if (i >= 10 && i % 2 === 1) {
const punctuation =
punctuationMarks[Math.floor(Math.random() * punctuationMarks.length)];
sentence[i] += punctuation;
}
}
return sentence.join(" ");
}
function updateSentence() {
while (currentSentenceIndex >= sentences.length) {
inputElement.value = "";
currentSentence = generateRandomSentence();
sentences.push(currentSentence);
// sentenceDiv.textContent = currentSentence;
// currentSentenceIndex = 0;
}
currentSentence = sentences[currentSentenceIndex];
sentenceDiv.textContent = currentSentence;
inputElement.value = "";
}
inputElement.addEventListener("input", (event) => {
// requestAnimationFrame(() => {
const currentInput = inputElement.value;
let newInnerHTML = "";
let errorOccurred = false;
let errorIndex = -1;
for (let i = 0; i < currentInput.length; i++) {
const typedChar = currentInput[i];
const sentenceChar = currentSentence[i];
if (!charStats[typedChar]) {
charStats[typedChar] = { totalTyped: 0, totalCorrect: 0, timestamps: [] };
}
if (typedChar === sentenceChar) {
newInnerHTML += `<span class="green">${sentenceChar}</span>`;
// Count the stat only if its the most recent character not after an error
if (i === currentInput.length - 1 && errorIndex === -1) {
// If there hasn't been 10 seconds since the last character, add the time-to-click to the character's array
const currentTime = new Date().getTime();
if (prevTimestamp != -1) {
charStats[sentenceChar].totalTyped++;
charStats[sentenceChar].totalCorrect++;
const timeDiff = currentTime - prevTimestamp;
console.log("Timediff", timeDiff);
if (timeDiff < 5 * 1000) {
charStats[sentenceChar].timestamps.push(timeDiff);
}
}
prevTimestamp = currentTime;
}
} else {
if (errorIndex === -1) {
errorIndex = i;
}
newInnerHTML += `<span class="red">${
typedChar == " " ? "␣" : typedChar
}</span>`;
// If we just missed this character, update the statistics
if (i === errorIndex && currentInput.length === errorIndex + 1) {
// Ignore wrong characters past the current input
if (i == currentInput.length - 1) {
charStats[sentenceChar].totalTyped++;
}
if (!missedKeys[sentenceChar]) {
missedKeys[sentenceChar] = 0;
}
missedKeys[sentenceChar]++;
if (!mistakeKeys[typedChar]) {
mistakeKeys[typedChar] = 0;
}
mistakeKeys[typedChar]++;
if (i > 0) {
const previousChar = currentInput[i - 1];
const keyPair = previousChar + sentenceChar;
if (!missedKeyPairs[keyPair]) {
missedKeyPairs[keyPair] = 0;
}
missedKeyPairs[keyPair]++;
const mistakeKeyPair = previousChar + typedChar;
if (!mistakeKeyPairs[keyPair]) {
mistakeKeyPairs[keyPair] = 0;
}
mistakeKeyPairs[keyPair]++;
}
}
}
// }
}
// if (errorIndex !== -1) {
// inputElement.value = currentInput.slice(0, errorIndex + 1);
// }
sentenceDiv.innerHTML =
newInnerHTML + currentSentence.slice(currentInput.length);
if (currentInput === currentSentence) {
currentSentenceIndex++;
updateSentence();
}
calculateStats();
calculateMostMissedKeys();
calculateMostMissedKeyPairs();
});
function saveStats() {
localStorage.setItem("charStats", JSON.stringify(charStats));
localStorage.setItem("missedKeys", JSON.stringify(missedKeys));
localStorage.setItem("missedKeyPairs", JSON.stringify(missedKeyPairs));
localStorage.setItem("mistakeKeys", JSON.stringify(mistakeKeys));
localStorage.setItem("mistakeKeyPairs", JSON.stringify(mistakeKeyPairs));
}
function loadStats() {
const loadedCharStats = localStorage.getItem("charStats");
const loadedMissedKeys = localStorage.getItem("missedKeys");
const loadedMissedKeyPairs = localStorage.getItem("missedKeyPairs");
const loadedMistakeKeys = localStorage.getItem("mistakeKeys");
const loadedMistakeKeyPairs = localStorage.getItem("mistakeKeyPairs");
if (loadedCharStats) {
charStats = JSON.parse(loadedCharStats);
}
if (loadedMissedKeys) {
missedKeys = JSON.parse(loadedMissedKeys);
}
if (loadedMissedKeyPairs) {
missedKeyPairs = JSON.parse(loadedMissedKeyPairs);
}
if (loadedMistakeKeys) {
mistakeKeys = JSON.parse(loadedMistakeKeys);
}
if (loadedMistakeKeyPairs) {
mistakeKeyPairs = JSON.parse(loadedMistakeKeyPairs);
}
}
function calculateStats() {
const currentTime = new Date().getTime();
let statsHTML = "";
const sortedChars = Object.keys(charStats).sort();
for (const char of sortedChars) {
const stats = charStats[char];
const discountFactor = 0.9;
const weightedTimestamps = stats.timestamps.map((timestamp, index) => {
return timestamp * Math.pow(discountFactor, index);
});
const sumWeightedTimestamps = weightedTimestamps.reduce(function (a, b) {
return a + b;
}, 0);
let normalization_constant = (Math.pow(discountFactor, weightedTimestamps.length) - 1) / (discountFactor - 1);
const avgWeightedTimestamps = sumWeightedTimestamps / normalization_constant;
const avgCharsPerWord = 5; // This doesn't include the space
const wpm = (60 * 1000) / (avgWeightedTimestamps * avgCharsPerWord);
console.log(
"Stats for ", char, ": ",
avgWeightedTimestamps,
avgCharsPerWord,
sumWeightedTimestamps,
weightedTimestamps.length,
wpm
);
const accuracy = (stats.totalCorrect / stats.totalTyped) * 100;
const adjustedWpm = isNaN(wpm) ? 0 : Math.pow(accuracy / 100, 2) * wpm;
const greenComponent = Math.min(255, Math.round(adjustedWpm * 2))
.toString(16)
.padStart(2, "0");
const redComponent = (255 - Math.min(255, Math.round(adjustedWpm * 2)))
.toString(16)
.padStart(2, "0");
const color = "#" + redComponent + greenComponent + "00";
statsHTML += `<div style="color: ${color}">${
char == " " ? "␣" : char
}: WPM = ${adjustedWpm.toFixed(
2
)}, Accuracy = ${accuracy.toFixed(2)}%</div>`;
}
const statsDiv: HTMLElement = document.getElementById("stats")!;
statsDiv.innerHTML = statsHTML;
}
function calculateMostMissedKeys() {
const keysAndCounts = Object.entries(missedKeys);
const top10 = keysAndCounts.sort((a, b) => b[1] - a[1]).slice(0, 10);
const missedKeysDiv: HTMLElement = document.getElementById("missed-keys")!;
missedKeysDiv.innerHTML =
"Top 10 missed keys:<br>" +
top10
.map(([key, count]) => `${key == " " ? "␣" : key}: ${count}`)
.join("<br>");
}
function calculateMostMissedKeyPairs() {
const pairsAndCounts = Object.entries(missedKeyPairs);
const top10 = pairsAndCounts.sort((a, b) => b[1] - a[1]).slice(0, 10);
const missedKeyPairsDiv: HTMLElement =
document.getElementById("missed-key-pairs")!;
missedKeyPairsDiv.innerHTML =
"Top 10 missed key pairs:<br>" +
top10
.map(([pair, count]) => `${pair.replace(" ", "␣")}: ${count}`)
.join("<br>");
}