html Copy code
<script>
class PreferenceRank {
constructor() {
this.state = this.getInitialState();
this.config = this.getConfig();
this.init();
}
$(id) {
return document.getElementById(id);
}
getInitialState() {
return {
items: [],
scores: {},
currentPair: [],
remainingPairs: [],
totalPairs: 0,
currentProgress: 0,
[Redacted Person]: false,
language: 'en',
history: []
};
}
getConfig() {
return {
INITIAL_RATING: 1000,
K_FACTOR: 32,
translations: {
en: {
title: "PreferenceRank",
itemInputLabel: "Enter items, one per line:",
[Redacted Person]: "Allow Ties",
alert: "Please enter at least two items.",
startButton: "Start Ranking",
likeBothButton: "Like Both",
[Redacted Person]: "Dislike Both",
undoButton: "Undo",
progress: "Progress",
results: "Results",
rank: "Rank",
item: "Item",
score: "Score",
restartBattleButton: "Restart Battle",
restartNewItemsButton: "Start with New Items"
},
id: {
title: "PreferenceRank",
itemInputLabel: "Masukkan pilihan, satu per baris:",
[Redacted Person]: "Izinkan Seri",
alert: "Harap masukkan setidaknya dua pilihan.",
startButton: "Mulai Peringkat",
likeBothButton: "Suka Keduanya",
dislikeBothButton: "Tidak Suka Keduanya",
undoButton: "Urungkan",
progress: "Kemajuan",
results: "Hasil",
rank: "Peringkat",
item: "Nama",
score: "Skor",
restartBattleButton: "Mulai Ulang Pertarungan",
restartNewItemsButton: "Mulai dengan Pilihan Baru"
}
}
};
}
init() {
// Bind all UI actions
["languageSelect", "allowTies", "startButton", "leftItem", "rightItem", "likeBothButton", "dislikeBothButton", "restartBattleButton", "restartNewItemsButton", "undoButton"]
.forEach(id => this.$(id)?.addEventListener("click", () => this.handleAction(id)));
this.updateLanguage();
}
handleAction(action) {
const actions = {
languageSelect: () => this.updateLanguage(),
allowTies: () => this.toggleTieOptions(),
startButton: () => this.startRank(),
leftItem: () => this.choose("left"),
rightItem: () => this.choose("right"),
likeBothButton: () => this.choose("tie"),
dislikeBothButton: () => this.choose("tie"),
restartBattleButton: () => this.restartBattle(),
restartNewItemsButton: () => this.restartNewItems(),
undoButton: () => this.undo()
};
actions[action]?.();
}
updateLanguage() {
const lang = this.$("languageSelect").value;
this.state.language = lang;
const t = this.config.translations[lang];
Object.entries(t).forEach(([key, value]) => this.$(key)?.textContent = value);
this.updateProgress();
if (this.$("results").style.display !== "none") this.showResults();
}
startRank() {
const items = this.$("itemInput").value.split("\n").map(i => i.trim()).filter(Boolean);
if (items.length < 2) return alert(this.config.translations[this.state.language].alert);
this.state = {
...this.state,
items,
allowTies: this.$("allowTies").checked,
scores: Object.fromEntries(items.map(i => [i, this.config.INITIAL_RATING])),
remainingPairs: this.shuffleArray(
items.flatMap((v, i) => items.slice(i + 1).map(w => [v, w]))
),
totalPairs: (items.length * (items.length - 1)) / 2,
currentProgress: 0,
history: []
};
this.showSection("battleSection");
this.$("tieButtons").style.display = this.state.allowTies ? "flex" : "none";
this.nextBattle();
}
choose(winner) {
const [left, right] = this.state.currentPair;
const result = winner === "left" ? 1 : winner === "right" ? 0 : 0.5;
const expected = 1 / (1 + 10 ** ((this.state.scores[right] - this.state.scores[left]) / 400));
this.state.history.push({ left, right, state: { ...this.state } });
this.state.scores[left] += this.config.K_FACTOR * (result - expected);
this.state.scores[right] += this.config.K_FACTOR * ((1 - result) - (1 - expected));
this.state.currentProgress++;
this.updateProgress();
this.nextBattle();
}
nextBattle() {
if (!this.state.remainingPairs.length) return this.showResults();
this.state.currentPair = this.state.remainingPairs.pop();
["left", "right"].forEach((side, i) => this.$(`${side}Item`).textContent = this.state.currentPair[i]);
this.updateProgress();
}
updateProgress() {
const t = this.config.translations[this.state.language];
this.$("progress").textContent = `${t.progress}: ${this.state.currentProgress}/${this.state.totalPairs}`;
}
undo() {
if (!this.state.history.length) return;
const { state } = this.state.history.pop();
this.state = { ...state };
this.nextBattle();
}
restartBattle() {
this.startRank();
}
restartNewItems() {
this.state = this.getInitialState();
this.showSection("inputSection");
this.$("itemInput").value = "";
}
showResults() {
const t = this.config.translations[this.state.language];
const sortedScores = Object.entries(this.state.scores).sort(([, a], [, b]) => b - a);
this.$("results").innerHTML = `
<h2>${t.results}</h2>
<table>
<thead><tr><th>${t.rank}</th><th>${t.item}</th><th>${t.score}</th></tr></thead>
<tbody>
${sortedScores.map(([item, score], i) => `<tr><td>${i + 1}</td><td>${item}</td><td>${Math.round(score)}</td></tr>`).join("")}
</tbody>
</table>`;
this.showSection("results");
}
showSection(id) {
["inputSection", "battleSection", "results"].forEach(sec => {
this.$(sec).style.display = sec === id ? "block" : "none";
});
}
shuffleArray(arr) {
return arr.sort(() => Math.random() - 0.5);
}
}
new PreferenceRank();
</script>
Kode ini mempertahankan semua fitur dan fungsionalitas asli, tetapi lebih efisien dan lebih mudah dipelihara.