github.com/enetx/g@v1.0.80/examples/iter/iter_flatten.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/enetx/g"
     7  	"github.com/enetx/g/f"
     8  )
     9  
    10  func main() {
    11  	// Example 1: Flatten a slice containing various types of elements
    12  	g.Slice[any]{
    13  		1,                            // integer
    14  		g.SliceOf(2, 3),              // slice of integers
    15  		"abc",                        // string
    16  		g.SliceOf("awe", "som", "e"), // slice of strings
    17  		g.SliceOf("co", "ol"),        // another slice of strings
    18  		g.SliceOf(4.5, 6.7),          // slice of floats
    19  		map[string]string{"a": "ss"}, // map with string keys and values
    20  		g.SliceOf(
    21  			g.MapOrd[int, int]{{1, 1}}, // slice of ordered maps
    22  			g.MapOrd[int, int]{{2, 2}}),
    23  	}.
    24  		Iter().    // creates an iterator for subsequent operations
    25  		Flatten(). // flattens nested slices, transforming them into a flat slice
    26  		Collect(). // gathers the elements of the iterator into a new slice.
    27  		Print()
    28  		// outputs the elements of the slice to the console. Slice[1, 2, 3, abc, awe, som, e, co, ol, 4.5, 6.7, map[a:ss], {1 1}, {2 2}]
    29  
    30  	// Example 2: Flatten a slice of strings by individual characters
    31  	words := g.SliceOf[g.String]("alpha", "beta", "gamma", "πŸ’›πŸ’šπŸ’™πŸ’œ", "δΈ–η•Œ")
    32  
    33  	// MapSlice applies a mapping function to each element of the source slice and returns a new slice.
    34  	// In this example, it maps each string in 'words' to its individual characters.
    35  	g.SliceMap(words, func(w g.String) g.Slice[g.String] { return w.Chars().Collect() }).
    36  		// g.SliceMap(words, g.String.Chars).
    37  		AsAny(). // Required if the source slice is not of type g.Slice[any]
    38  		Iter().
    39  		Flatten().
    40  		Collect().
    41  		Join().
    42  		Print() // alphabetagammaπŸ’›πŸ’šπŸ’™πŸ’œδΈ–η•Œ
    43  
    44  	// Example 3: Check if the flattened slice contains a specific element
    45  	ch := g.Slice[g.Slice[string]]{{"a", "b", "c"}, {"d", "f", "g"}}.
    46  		AsAny(). // g.Slice[any]{g.Slice[string]{"a", "b", "c"}, g.Slice[string]{"d", "f", "g"}}
    47  		Iter().
    48  		Flatten().
    49  		Collect() // g.Slice[any]{"a", "b", "c", "d", "f", "g"}
    50  
    51  	fmt.Println(ch.Contains("x"))              // false
    52  	fmt.Println(ch.Contains("a"))              // true
    53  	fmt.Println(ch.Contains(4444))             // false
    54  	fmt.Println(ch.ContainsBy(f.Eq[any]("c"))) // true
    55  }