#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MindmapNode {
pub text: String,
pub children: Vec<MindmapNode>,
}
impl MindmapNode {
pub fn new(text: impl Into<String>) -> Self {
MindmapNode {
text: text.into(),
children: Vec::new(),
}
}
pub fn node_count(&self) -> usize {
1 + self.children.iter().map(MindmapNode::node_count).sum::<usize>()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mindmap {
pub root: MindmapNode,
}
impl Default for Mindmap {
fn default() -> Self {
Mindmap {
root: MindmapNode::new("root"),
}
}
}
impl Mindmap {
pub fn node_count(&self) -> usize {
self.root.node_count()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_mindmap_has_one_node() {
let m = Mindmap::default();
assert_eq!(m.node_count(), 1);
assert_eq!(m.root.text, "root");
assert!(m.root.children.is_empty());
}
#[test]
fn node_count_counts_all_descendants() {
let diag = Mindmap {
root: MindmapNode {
text: "root".to_string(),
children: vec![
MindmapNode {
text: "A".to_string(),
children: vec![MindmapNode::new("A1"), MindmapNode::new("A2")],
},
MindmapNode::new("B"),
],
},
};
assert_eq!(diag.node_count(), 5);
}
#[test]
fn equality_holds_for_identical_trees() {
let a = Mindmap {
root: MindmapNode {
text: "root".to_string(),
children: vec![MindmapNode::new("child")],
},
};
let b = a.clone();
assert_eq!(a, b);
let c = Mindmap {
root: MindmapNode {
text: "root".to_string(),
children: vec![MindmapNode::new("other")],
},
};
assert_ne!(a, c);
}
}