feat: quality-of-life improvements

This commit is contained in:
apio 2023-01-11 23:22:24 +01:00
parent 73210bba78
commit 968c6d851f
Signed by: apio
GPG Key ID: B8A7D06E42258954

View File

@ -23,6 +23,28 @@ async function updateTarget() {
console.log("ready!"); console.log("ready!");
} }
const levenshteinDistance = (str1, str2) => {
const track = Array(str2.length + 1).fill(null).map(() =>
Array(str1.length + 1).fill(null));
for (let i = 0; i <= str1.length; i += 1) {
track[0][i] = i;
}
for (let j = 0; j <= str2.length; j += 1) {
track[j][0] = j;
}
for (let j = 1; j <= str2.length; j += 1) {
for (let i = 1; i <= str1.length; i += 1) {
const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
track[j][i] = Math.min(
track[j][i - 1] + 1, // deletion
track[j - 1][i] + 1, // insertion
track[j - 1][i - 1] + indicator, // substitution
);
}
}
return track[str2.length][str1.length];
};
function isLetter(str) { function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i); return str.length === 1 && str.match(/[a-z]/i);
} }
@ -30,6 +52,11 @@ function isLetter(str) {
updateSpellField = (text) => { updateSpellField = (text) => {
field.innerText = text; field.innerText = text;
field.style.color = ""; field.style.color = "";
if(text.length == 0) {
field.innerText = "escribe algo...";
field.style.color = "gray";
}
} }
updateScores = () => { updateScores = () => {
@ -41,11 +68,15 @@ updateScores = () => {
} }
submitBuffer = () => { submitBuffer = () => {
if(buffer.toLowerCase() !== target.toLowerCase()) let distance = levenshteinDistance(buffer.toLowerCase(), target.toLowerCase());
if(distance > 1)
{ {
updateSpellField(target); updateSpellField(target);
field.style.color = "red"; field.style.color = "red";
failedAttempts += 1; failedAttempts += 1;
} else if(distance > 0) {
updateSpellField(target);
field.style.color = "yellow";
} else { } else {
updateSpellField(buffer); updateSpellField(buffer);
field.style.color = "green"; field.style.color = "green";
@ -64,6 +95,11 @@ document.onkeyup = (ev) => {
{ {
if(buffer.length != 0) submitBuffer(); if(buffer.length != 0) submitBuffer();
} }
if(key === "Backspace")
{
buffer = buffer.slice(0, buffer.length - 1);
updateSpellField(buffer);
}
if(isLetter(key)) if(isLetter(key))
{ {
buffer += key; buffer += key;