debreviator/src/main/js/main.js

77 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-11-28 18:25:16 +01:00
// noinspection JSUnresolvedVariable
2022-11-21 23:05:16 +01:00
const {$, doAfterLoad} = window.fwdekker;
// noinspection JSUnresolvedVariable
const {clearFormValidity, showInputInvalid} = window.fwdekker.validation;
2021-11-28 18:25:16 +01:00
function toUppercaseAt(string, index) {
return string.slice(0, index) + string.charAt(index).toUpperCase() + string.slice(index + 1);
}
doAfterLoad(() => {
2022-11-21 23:05:16 +01:00
const debreviateForm = $("#debreviate-form");
2021-12-01 22:00:21 +01:00
const abbreviationInput = $("#abbreviation");
const abbreviationError = $("#abbreviation-error");
const debreviationOutput = $("#debreviations");
const showError = (message) => {
if (message === undefined) {
abbreviationError.innerText = "";
debreviationOutput.classList.remove("hidden");
} else {
abbreviationError.innerText = message;
debreviationOutput.classList.add("hidden");
}
};
2021-11-28 18:25:16 +01:00
const debreviate = () => {
2022-11-21 23:05:16 +01:00
clearFormValidity(debreviateForm);
2021-12-01 22:00:21 +01:00
const abbreviation = abbreviationInput.value.trim();
if (abbreviation === "") {
2022-11-21 23:05:16 +01:00
showInputInvalid(abbreviationInput, "Abbreviation should be non-empty.");
2021-12-01 22:00:21 +01:00
return;
}
2021-11-28 18:25:16 +01:00
const regex = new RegExp(abbreviation.split("").join(".*"));
fetch("words.txt")
.then(it => it.text())
.then(text => text.split("\n").filter(it => !it.startsWith("#")).map(it => it.toLowerCase()))
.then(words => words.filter(it => regex.test(it)))
.then(matches =>
matches.map(match =>
abbreviation
.split("")
.reduce(
(acc, letter) => {
const letterIndex = acc[0].indexOf(letter, acc[1]);
return [toUppercaseAt(acc[0], letterIndex), letterIndex];
},
[match, 0]
)[0]
)
)
2021-12-01 22:00:21 +01:00
.then(matches => {
if (matches.length === 0) {
showError("No debreviations found.");
return;
}
debreviationOutput.value = matches.join("\n");
showError();
});
2021-11-28 18:25:16 +01:00
};
2022-11-21 23:05:16 +01:00
debreviateForm.addEventListener("submit", event => {
event.preventDefault();
debreviate();
2021-11-28 18:25:16 +01:00
});
2022-11-21 23:05:16 +01:00
// Show page to user
$("main").classList.remove("hidden");
$("[autofocus]").focus();
2021-11-28 18:25:16 +01:00
});