Skip to content

Instantly share code, notes, and snippets.

@ilsubyeega
Created December 9, 2023 06:45
Show Gist options
  • Save ilsubyeega/7aad2700dc170c3070bf1bb0c714cb93 to your computer and use it in GitHub Desktop.
Save ilsubyeega/7aad2700dc170c3070bf1bb0c714cb93 to your computer and use it in GitHub Desktop.
Markdown to Anki

Chapter 01

  • AB
  • Problem 01
    • Answer A
    • Answer B
    • Answer C
    • Answer D
  • Problem 02
    • Answer A
    • Answer B
    • Answer C
    • Answer D

Chapter 02

  • AB
  • Problem 01
    • Answer A
    • Answer B
    • Answer C
    • Answer D
  • Problem 02
    • Answer A
    • Answer B
    • Answer C
    • Answer D
const fs = require('fs')
const file = fs.readFileSync('example.md', 'utf8').trim()
const res = file.split("#")
.map(a => a.trim())
.filter(a => a)
.map(a => {
let list = a.split("\r\n")
const chapter = list.shift().trim()
const answers = list.shift().replace("- ", "").trim()
const raw_questions = list.map(a => a)
let temp_list = [];
raw_questions.forEach(a => {
if (a.startsWith("- ")) {
temp_list.push({
question: a.replace("- ", "").trim(),
choices: []
})
} else if (a.startsWith(" - ")) {
temp_list[temp_list.length - 1].choices.push(a.replace(" - ", "").trim())
} else {
throw new Error(a)
}
})
return [chapter, answers, temp_list]
})
.map(a => {
const answer_map = "ABCD";
[chapter, answers, temp_list] = a
temp_list.map((a, i) => {
a.answer = answer_map.indexOf(answers[i])
a.answer_text = a.choices[a.answer]
return a
})
return {
chapter,
questions: temp_list
}
});
console.log(res)
console.log(res.map(a => a.questions.length))
const anki_format = res.map(a => {
const { chapter, questions } = a
let list = questions.map(q =>
[
q.question,
chapter,
2,
q.choices.join("\t"),
"",
q.choices.map((_, i) => i == q.answer ? 1 : 0).join(" ")
].join("\t"))
list.unshift("#separator:tab")
list.unshift("#html:false")
list.unshift("#tags column:12")
return list.join("\r\n")
});
console.log(anki_format)
// save files
anki_format.forEach((a, i) => {
fs.writeFileSync(`${i + 1}.txt`, a)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment