@@ -30,6 +30,42 @@ impl<T: fmt::Display> FromIterator<T> for Checkbox {
3030}
3131
3232impl Checkbox {
33+ /// Creates a `Checkbox` from an iterator of tuples where the first element
34+ /// implements the `Display` trait and the second element is a bool indicating
35+ /// if the item is picked (selected).
36+ /// Each item is added to the listbox, and the set of picked indices is
37+ /// initialized based on the bool values.
38+ pub fn new_with_checked < T : fmt:: Display , I : IntoIterator < Item = ( T , bool ) > > ( iter : I ) -> Self {
39+ let ( listbox, picked) : ( Vec < _ > , Vec < _ > ) = iter
40+ . into_iter ( )
41+ . enumerate ( )
42+ . map ( |( index, ( item, is_picked) ) | ( ( index, item) , is_picked) )
43+ . unzip ( ) ; // `unzip` を使用して、アイテムと選択状態を分けます。
44+
45+ let listbox_items = listbox
46+ . into_iter ( )
47+ . map ( |( _, item) | item)
48+ . collect :: < Vec < _ > > ( ) ;
49+ let picked_indices = picked
50+ . into_iter ( )
51+ . enumerate ( )
52+ . filter_map (
53+ |( index, is_picked) | {
54+ if is_picked {
55+ Some ( index)
56+ } else {
57+ None
58+ }
59+ } ,
60+ )
61+ . collect :: < HashSet < usize > > ( ) ;
62+
63+ Self {
64+ listbox : Listbox :: from_iter ( listbox_items) ,
65+ picked : picked_indices,
66+ }
67+ }
68+
3369 /// Returns a reference to the vector of items in the listbox.
3470 pub fn items ( & self ) -> & Vec < String > {
3571 self . listbox . items ( )
@@ -86,3 +122,35 @@ impl Checkbox {
86122 self . listbox . move_to_tail ( )
87123 }
88124}
125+
126+ #[ cfg( test) ]
127+ mod tests {
128+ use super :: * ;
129+
130+ mod new_with_checked {
131+ use super :: * ;
132+
133+ #[ test]
134+ fn test ( ) {
135+ // Prepare a list of items with their checked status
136+ let items = vec ! [
137+ ( String :: from( "1" ) , true ) ,
138+ ( String :: from( "2" ) , false ) ,
139+ ( String :: from( "3" ) , true ) ,
140+ ] ;
141+
142+ // Create a Checkbox using `new_with_checked`
143+ let checkbox = Checkbox :: new_with_checked ( items) ;
144+
145+ // Verify the items in the listbox
146+ assert_eq ! (
147+ checkbox. items( ) ,
148+ & vec![ "1" . to_string( ) , "2" . to_string( ) , "3" . to_string( ) ]
149+ ) ;
150+
151+ // Verify the picked (selected) indices
152+ let expected_picked_indexes: HashSet < usize > = [ 0 , 2 ] . iter ( ) . cloned ( ) . collect ( ) ;
153+ assert_eq ! ( checkbox. picked_indexes( ) , & expected_picked_indexes) ;
154+ }
155+ }
156+ }
0 commit comments