hugo-batsite/public/js/randomword.js

39 lines
937 B
JavaScript
Raw Normal View History

2022-04-16 20:02:16 +00:00
const buttons = document.getElementsByClassName("randomword-button");
export function randomizeWords() {
registerButtons();
}
function registerButtons() {
for (let button of buttons) {
button.addEventListener("click", function () {
2022-04-16 21:03:26 +00:00
button.innerHTML = processWordlist(
button.getAttribute("data-wordlist"),
button.innerHTML
);
2022-04-16 20:02:16 +00:00
// do this so people dont have to click twice
});
button.click();
}
}
// takes all the words and returns only one
2022-04-16 21:03:26 +00:00
function processWordlist(wordlist, old) {
2022-04-16 20:02:16 +00:00
let seperated = wordlist.split(",");
2022-04-16 21:03:26 +00:00
for (let word of wordlist) {
word = word.trim();
}
if (seperated.length <= 0) {
return "error! empty";
}
if (seperated.length == 1) {
return seperated[0];
}
seperated = seperated.filter((e) => e !== old);
2022-04-16 20:02:16 +00:00
return seperated.random();
}
Array.prototype.random = function () {
return this[Math.floor(Math.random() * this.length)];
};