Apologies for the bad title, someone can suggest me a better title.
I'm building a simple flashcard app in Golang. The following code returns one side of the flashcard, waits for a [ENTER], returns the other side.
I want to include a way to mark certain cards which I forgot, to add them back to the range, so they are displayed later in my revision session. This maybe done by just checking for a specific determined input at the fmt.Scanln()
The problem is, I also need a limit function, like the one I have included. -n
limits the cards displayed. Just adding the cards to the map may not add it to the n
cards in memory in the current session.
import (
"encoding/csv"
"flag"
"fmt"
"log"
"math/rand"
"os"
"os/exec"
"runtime"
"time"
"github.com/fatih/color"
)
var (
flagNoColor = flag.Bool("no-color", false, "disable color output")
csvPath = flag.String("src", "src.csv", "source")
lang = flag.String("lang", "random", "language")
num = flag.Int("n", -1, "number")
)
var clear map[string]func()
func init() {
clear = make(map[string]func())
clear["linux"] = func() {
cmd := exec.Command("clear")
cmd.Stdout = os.Stdout
cmd.Run()
}
clear["windows"] = func() {
cmd := exec.Command("cmd", "/c", "cls")
cmd.Stdout = os.Stdout
cmd.Run()
}
}
func CallClear() {
value, ok := clear[runtime.GOOS]
if ok {
value()
} else {
panic("Panic!")
}
}
func random(min int, max int) int {
return rand.Intn((max-min) + 1) + min
}
func main() {
flag.Parse()
file, err := os.Open(*csvPath)
if err != nil {
log.Println(err)
return
}
defer file.Close()
csvReader := csv.NewReader(file)
csvData, err := csvReader.ReadAll()
if err != nil {
log.Println(err)
return
}
qaPair := make(map[string]string, len(csvData))
for _, data := range csvData {
qaPair[data[0]] = data[1]
}
done := make(chan bool)
breakF := make(chan bool)
qNum := 0
go func() {
if *flagNoColor {
color.NoColor = true
}
white := color.New(color.FgWhite)
boldWhite := white.Add(color.Bold)
for one, two := range qaPair {
if qNum == *num {
breakF <- true
}
rand.Seed(time.Now().UnixNano())
randomNum := random(1, 2)
CallClear()
if *lang == "es" {
randomNum = 1
} else if *lang == "en" {
randomNum = 2
}
qNum++
boldWhite.Printf("
# %d / %d
", qNum, len(qaPair))
if randomNum == 1 {
boldWhite.Printf("
Q %s", one)
fmt.Scanln()
boldWhite.Printf("
A %s", two)
fmt.Scanln()
} else {
boldWhite.Printf("
Q %s", two)
fmt.Scanln()
boldWhite.Printf("
A %s", one)
fmt.Scanln()
}
CallClear()
}
done <- true
}()
select {
case <-done:
case <-breakF:
}
}