Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

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

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

-t- forward

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.