Skip to content

Instantly share code, notes, and snippets.

@lhauspie
Last active October 17, 2018 07:41
Show Gist options
  • Save lhauspie/4911f3777605f9eec4d4c7299a747651 to your computer and use it in GitHub Desktop.
Save lhauspie/4911f3777605f9eec4d4c7299a747651 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
fn main() {
println!("Hello, world!");
}
struct Dependencies {
deps : HashMap<String, Vec<String>>
}
impl Dependencies {
fn new() -> Self {
Dependencies{deps: HashMap::new()}
}
fn depFor(&self, node: String) -> Vec<String> {
match self.deps.get(&node) {
Some (v) => {
let mut result: Vec<String> = Vec::new();
result.append(&mut v.to_vec());
for n in v {
result.append(&mut self.depFor(n.to_string()));
}
result
},
None => vec![]
}
}
fn add_direct(&mut self, node: String, dependencies: Vec<String>){
self.deps.insert(node.to_string(), dependencies.into_iter().map(|x| x.to_string()).collect());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_dep() {
let dep = Dependencies::new();
let expected : Vec<String> = Vec::new();
assert_eq!(dep.depFor(String::from("A")), expected);
}
#[test]
fn a_dep_b() {
let mut dep = Dependencies::new();
dep.add_direct(String::from("A"),vec!(String::from("B")));
assert_eq!(dep.depFor(String::from("A")), ["B"]);
}
#[test]
fn a_dep_b_c(){
let mut dep = Dependencies::new();
dep.add_direct(String::from("A"),vec!(String::from("B"), String::from("C")));
assert_eq!(dep.depFor(String::from("A")), vec!("B", "C"));
}
#[test]
fn a_dep_b_dep_c(){
let mut dep = Dependencies::new();
dep.add_direct(String::from("A"),vec!(String::from("B")));
dep.add_direct(String::from("B"), vec!(String::from("C")));
assert_eq!(dep.depFor(String::from("A")), vec!("B", "C"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment