ManevilleF/hexx

Return `ExactSizeIterator` from shapes where possible

alice-i-cecile opened this issue · 1 comments

hexx/src/lib.rs

Line 156 in 9e7dc16

pub fn hexagon(center: Hex, radius: u32) -> impl Iterator<Item = Hex> {

This avoids needing to slowly count the iterator. This was particularly silly because iterators are consumed by doing so.

See this code that I wrote:

    /// Returns the average height of tiles around `tile_pos` within `radius`
    pub(crate) fn average_height(&self, tile_pos: TilePos, radius: u32) -> f32 {
        let hex_iter = hexagon(tile_pos.hex, radius);
        let n = hex_iter.count();
        let hex_iter = hexagon(tile_pos.hex, radius);
        let heights = hex_iter.map(|hex| *self.height_index.get(&TilePos { hex }).unwrap_or(&0.));
        heights.sum::<f32>() / n as f32
    }

I like the idea of a ExactSizeIterator implementation where I know the amount of coordinates.

For your use case there is a helper method Hex::range_count which gives you the amount of coordinates in a hex range.

Therefore you can edit your method as following:

/// Returns the average height of tiles around `tile_pos` within `radius`
    pub(crate) fn average_height(&self, tile_pos: TilePos, radius: u32) -> f32 {
        let hex_iter = hexagon(tile_pos.hex, radius);
        let n = Hex::range_count(radius);
        let heights = hex_iter.map(|hex| *self.height_index.get(&TilePos { hex }).unwrap_or(&0.));
        heights.sum::<f32>() / n as f32
    }