home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Find The Previous Or Next Item Matching A Search In A Rust Vec

March 2024

There's probably a more native way to do this or a more refined data strucutre approach. Let me know if there are more straight-forwards solutions.

Code
fn main() {
  let items = vec!["a".to_string(), "b".to_string(), "c".to_string()];

  assert_eq!(prev_item_before("a".to_string(), &items), None);
  assert_eq!(prev_item_before("c".to_string(), &items), Some(&items[1]));
  assert_eq!(prev_item_before("d".to_string(), &items), None);

  assert_eq!(next_item_after("a".to_string(), &items), Some(&items[1]));
  assert_eq!(next_item_after("c".to_string(), &items), None);
  assert_eq!(next_item_after("d".to_string(), &items), None);

  println!("all tests passed");
}

fn prev_item_before<'a>(key: String, items: &'a Vec<String>) -> Option<&'a String> {
   match items.iter().position(|item| item == &key) {
    Some(index) => {
      if index > 0 {
        items.get(index - 1)
      } else {
        None 
      }
    },
    None => None
  }
}

fn next_item_after<'a>(key: String, items: &'a Vec<String>) -> Option<&'a String> {
  match items.iter().position(|item| item == &key) {
    Some(index) => items.get(index + 1),
    None => None
  }
}
Results
all tests passed
═══ § ═══