-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
88 lines (76 loc) · 2.48 KB
/
script.js
File metadata and controls
88 lines (76 loc) · 2.48 KB
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
const localStorageDeckKey = "deck"
class Card {
constructor(question, answer) {
this.question = question
this.answer = answer
}
}
class Deck {
cards = []
setCardsFromDict(data) {
this.cards = []
for (const entry in data) {
this.cards.push(new Card(entry, data[entry]))
}
}
drawRandomCard() {
const index = Math.floor(Math.random() * this.cards.length)
const card = this.cards[index]
this.cards.splice(index, 1)
return card
}
getRemainingCards() {
return this.cards.length
}
}
const deck = new Deck()
function loadDeckFromFile() {
const file = document.getElementById('file-input').files[0]
const reader = new FileReader()
reader.onload = e => {
try {
const lines = e.target.result.split("\n")
const newCards = {}
for (const line of lines) {
const items = line.replace("\r", "").split(",")
if (items.length != 2) throw new Error()
newCards[items[0]] = items[1]
}
deck.setCardsFromDict(newCards)
$("#cards-total-counter").text(Object.keys(newCards).length)
window.localStorage.setItem(localStorageDeckKey, JSON.stringify(newCards))
showNewCard()
} catch (error) {
alert("Arquivo inválido. Certifique-se de que ele é um CSV.")
}
}
reader.readAsText(file)
}
function loadDeckFromLocalStorage() {
const newCards = JSON.parse(window.localStorage.getItem(localStorageDeckKey))
if (newCards) {
deck.setCardsFromDict(newCards)
$("#cards-total-counter").text(Object.keys(newCards).length)
showNewCard()
}
}
function showNewCard() {
const card = deck.drawRandomCard()
if (!card) {
alert("Concluído! Reiniciando")
loadDeckFromLocalStorage()
}
$("#question-card-content").text(card.question)
$("#answer-card-content").text(card.answer)
$("#cards-remaining-counter").text(deck.getRemainingCards())
$("#answer-card").hide()
}
function revealAnswer() {
$("#answer-card").show()
}
$(document).ready(function() {
loadDeckFromLocalStorage()
})
$(document).on('click', '#next-button', () => showNewCard())
$(document).on('click', '#reveal-button', () => revealAnswer())
$(document).on('click', '#load-file-button', () => loadDeckFromFile())