@@ -616,6 +616,48 @@ impl<T> Graph<T> {
616616 acc
617617 }
618618
619+ /// Performs a map over all of the vertices of the graph,
620+ /// applying the given transformation function to each one.
621+ ///
622+ /// Returns a new graph with the same edges but with transformed
623+ /// vertices.
624+ /// ## Example
625+ /// ```rust
626+ /// use graphlib::Graph;
627+ ///
628+ /// let mut graph: Graph<usize> = Graph::new();
629+ /// let id1 = graph.add_vertex(1);
630+ /// let id2 = graph.add_vertex(2);
631+ ///
632+ /// graph.add_edge(&id1, &id2);
633+ ///
634+ /// // Map each vertex
635+ /// let mapped: Graph<usize> = graph.map(|v| v + 2);
636+ ///
637+ /// assert!(graph.has_edge(&id1, &id2));
638+ /// assert!(mapped.has_edge(&id1, &id2));
639+ /// assert_eq!(graph.fetch(&id1).unwrap(), &1);
640+ /// assert_eq!(graph.fetch(&id2).unwrap(), &2);
641+ /// assert_eq!(mapped.fetch(&id1).unwrap(), &3);
642+ /// assert_eq!(mapped.fetch(&id2).unwrap(), &4);
643+ /// ```
644+ pub fn map < R > ( & self , fun : impl Fn ( & T ) -> R ) -> Graph < R > {
645+ let mut graph: Graph < R > = Graph :: new ( ) ;
646+
647+ // Copy edge and vertex information
648+ graph. edges = self . edges . clone ( ) ;
649+ graph. roots = self . roots . clone ( ) ;
650+ graph. tips = self . tips . clone ( ) ;
651+ graph. inbound_table = self . inbound_table . clone ( ) ;
652+ graph. outbound_table = self . outbound_table . clone ( ) ;
653+ graph. vertices = self . vertices
654+ . iter ( )
655+ . map ( |( id, ( v, i) ) | ( id. clone ( ) , ( fun ( v) , i. clone ( ) ) ) )
656+ . collect ( ) ;
657+
658+ graph
659+ }
660+
619661 /// Returns true if the graph has cycles.
620662 ///
621663 /// ```rust
0 commit comments