Guest User

Untitled

a guest
May 26th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. use std::collections::BTreeMap;
  2. use std::io::{self, Write};
  3.  
  4. pub struct Todo {
  5. name: String,
  6. checked: bool,
  7. priority: i32,
  8. }
  9.  
  10. impl Todo {
  11. pub fn write<W: Write>(&self, w: &mut W) {
  12. write!(w, "{}:\n", self.name);
  13. write!(w, "Checked: {}\n", self.checked);
  14. write!(w, "Priority: {}\n", self.priority);
  15. write!(w, "\n");
  16. }
  17.  
  18. pub fn print(&self) {
  19. self.write(&mut io::stdout());
  20. }
  21. }
  22.  
  23. #[derive(Default)]
  24. pub struct TodoList {
  25. list: BTreeMap<i32, Vec<Todo>>,
  26. }
  27.  
  28. impl TodoList {
  29. pub fn new() -> TodoList {
  30. TodoList {
  31. list: BTreeMap::new(),
  32. }
  33. }
  34.  
  35. pub fn add(&mut self, todo: Todo) {
  36. let list = self.list.entry(todo.priority).or_insert_with(Vec::new);
  37. list.push(todo);
  38. }
  39.  
  40. pub fn todos(&self) -> impl Iterator<Item = &Todo> {
  41. self.list.iter().flat_map(|(_, list)| list.iter())
  42. }
  43.  
  44. pub fn unchecked(&self) -> impl Iterator<Item = &Todo> {
  45. self.todos().filter(|t| !t.checked)
  46. }
  47.  
  48. pub fn checked(&self) -> impl Iterator<Item = &Todo> {
  49. self.todos().filter(|t| t.checked)
  50. }
  51. }
  52.  
  53. fn main() {
  54. let mut list = TodoList::new();
  55. list.add(Todo {
  56. name: "A".to_string(),
  57. checked: false,
  58. priority: 10,
  59. });
  60. list.add(Todo {
  61. name: "B".to_string(),
  62. checked: false,
  63. priority: 5,
  64. });
  65. list.add(Todo {
  66. name: "C".to_string(),
  67. checked: false,
  68. priority: 6,
  69. });
  70. list.add(Todo {
  71. name: "D".to_string(),
  72. checked: true,
  73. priority: 1,
  74. });
  75.  
  76. println!("Unchecked todos:");
  77. for todo in list.unchecked() {
  78. todo.print();
  79. }
  80.  
  81. println!("Checked todos:");
  82. for todo in list.checked() {
  83. todo.print();
  84. }
  85. }
Add Comment
Please, Sign In to add comment