From 934dc5cb7f49805a504e37e8fda428633ae0a0ea Mon Sep 17 00:00:00 2001 From: Johannes Date: Tue, 10 Dec 2024 19:19:04 +0100 Subject: [PATCH] added mapping to grid --- src/utils/grid.rs | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/utils/grid.rs b/src/utils/grid.rs index 3194613..0d92e3e 100644 --- a/src/utils/grid.rs +++ b/src/utils/grid.rs @@ -3,8 +3,10 @@ use std::{ ops::{Index, IndexMut}, }; +use itertools::Itertools; + /// A grid structure, indexed by (x, y) tuples. The top-left coordinate is (0, 0). -#[derive(Eq, PartialEq, Debug)] +#[derive(Eq, PartialEq, Debug, Clone)] pub struct Grid { pub content_width: i64, pub content_height: i64, @@ -85,10 +87,16 @@ impl Grid { val, ) }) - // .collect_vec() } - // todo: map from T to U + pub fn map_values(self, f: fn(T) -> U) -> Grid { + let new_content = self.content.into_iter().map(f).collect_vec(); + Grid { + content_width: self.content_width, + content_height: self.content_height, + content: new_content, + } + } } impl Grid { @@ -193,10 +201,16 @@ mod test { #[should_panic] #[test] - fn out_of_bounds_panics() { + fn out_of_bounds_panics1() { generate()[(-1, 3)]; } + #[should_panic] + #[test] + fn out_of_bounds_panics2() { + generate()[(1, 3)]; + } + #[test] fn option_success() { assert_eq!(Some(&'.'), generate().get((0, 0))); @@ -206,4 +220,11 @@ mod test { fn option_out_of_bounds() { assert_eq!(None, generate().get((30, 0))); } + + #[test] + fn value_mapping() { + let a: Grid = generate(); + let b: Grid = a.map_values(|old| format!("{old}string")); + assert_eq!(".string".to_string(), b[(0, 0)]); + } }