pub fn cloze(number: u32, text: &str) -> String {
format!("{{{{c{}::{}}}}}", number, text)
}
pub fn cloze_hint(number: u32, text: &str, hint: &str) -> String {
format!("{{{{c{}::{}::{}}}}}", number, text, hint)
}
#[derive(Debug, Default)]
pub struct ClozeBuilder {
counter: u32,
}
impl ClozeBuilder {
pub fn new() -> Self {
Self { counter: 0 }
}
pub fn add(&mut self, text: &str) -> String {
self.counter += 1;
cloze(self.counter, text)
}
pub fn add_with_hint(&mut self, text: &str, hint: &str) -> String {
self.counter += 1;
cloze_hint(self.counter, text, hint)
}
pub fn current(&self) -> u32 {
self.counter
}
pub fn reset(&mut self) {
self.counter = 0;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cloze() {
assert_eq!(cloze(1, "test"), "{{c1::test}}");
assert_eq!(cloze(2, "another"), "{{c2::another}}");
assert_eq!(cloze(10, "big number"), "{{c10::big number}}");
}
#[test]
fn test_cloze_hint() {
assert_eq!(cloze_hint(1, "Paris", "city"), "{{c1::Paris::city}}");
assert_eq!(cloze_hint(3, "H2O", "formula"), "{{c3::H2O::formula}}");
}
#[test]
fn test_cloze_builder() {
let mut builder = ClozeBuilder::new();
assert_eq!(builder.current(), 0);
let c1 = builder.add("first");
assert_eq!(c1, "{{c1::first}}");
assert_eq!(builder.current(), 1);
let c2 = builder.add("second");
assert_eq!(c2, "{{c2::second}}");
assert_eq!(builder.current(), 2);
let c3 = builder.add_with_hint("third", "hint");
assert_eq!(c3, "{{c3::third::hint}}");
assert_eq!(builder.current(), 3);
builder.reset();
assert_eq!(builder.current(), 0);
let c1_again = builder.add("new first");
assert_eq!(c1_again, "{{c1::new first}}");
}
#[test]
fn test_cloze_in_sentence() {
let sentence = format!(
"The {} is the capital of {}.",
cloze(1, "Paris"),
cloze(2, "France")
);
assert_eq!(
sentence,
"The {{c1::Paris}} is the capital of {{c2::France}}."
);
}
#[test]
fn test_cloze_builder_sentence() {
let mut builder = ClozeBuilder::new();
let sentence = format!(
"{} discovered {} in {}.",
builder.add("Marie Curie"),
builder.add("radium"),
builder.add_with_hint("1898", "year")
);
assert_eq!(
sentence,
"{{c1::Marie Curie}} discovered {{c2::radium}} in {{c3::1898::year}}."
);
}
}