### Install lang library Source: https://github.com/maxbolgarin/lang/blob/main/README.md Command to install the lang package via Go modules. ```bash go get -u github.com/maxbolgarin/lang ``` -------------------------------- ### Functional Composition and Pipeline Patterns Source: https://github.com/maxbolgarin/lang/blob/main/README.md Examples of chaining functional operations and implementing a generic pipeline structure for cleaner code. ```go result := lang.Filter( lang.Convert(rawData, parseUser), func(u User) bool { return u.IsValid() }, ) type Pipeline[T any] struct { data []T } func (p Pipeline[T]) Filter(fn func(T) bool) Pipeline[T] { return Pipeline[T]{lang.Filter(p.data, fn)} } ``` -------------------------------- ### Map Creation and Transformation from Slices (Go) Source: https://github.com/maxbolgarin/lang/blob/main/README.md Illustrates how to create maps from slices using different strategies. This includes mapping by a key function, transforming to arbitrary key-value pairs, and creating maps from string pairs. ```go // Create maps from slices users := []User{ {ID: 1, Name: "Alice", Email: "alice@example.com"}, {ID: 2, Name: "Bob", Email: "bob@example.com"}, } // Map by key function usersByID := lang.SliceToMapByKey(users, func(u User) int { return u.ID }) // usersByID: map[int]User{1: {ID: 1, Name: "Alice", ...}, 2: {ID: 2, Name: "Bob", ...}} // Transform to different key-value pairs emailMap := lang.SliceToMap(users, func(u User) (string, string) { return u.Name, u.Email }) // emailMap: map[string]string{"Alice": "alice@example.com", "Bob": "bob@example.com"} // Create from pairs pairs := []string{"name", "John", "age", "25", "city", "NYC"} config := lang.PairsToMap(pairs) // config: map[string]string{"name": "John", "age": "25", "city": "NYC"} ``` -------------------------------- ### Configuration Management in Go Source: https://github.com/maxbolgarin/lang/blob/main/README.md Shows how to load application configurations using default values and environment variables with the Lang library's safe checking utilities. ```go func loadConfig() Config { return Config{ Database: DatabaseConfig{ Host: lang.Check(os.Getenv("DB_HOST"), "localhost"), Port: lang.Check(parsePort(os.Getenv("DB_PORT")), 5432), Timeout: lang.Check(parseDuration(os.Getenv("DB_TIMEOUT")), 30*time.Second), }, Server: ServerConfig{ Port: lang.Check(parsePort(os.Getenv("SERVER_PORT")), 8080), Workers: lang.Check(parseWorkers(os.Getenv("WORKERS")), 4), }, Features: lang.PairsToMap(lang.NotEmpty(strings.Split(os.Getenv("FEATURES"), ","))), } } ``` -------------------------------- ### Pointer and Value Helpers Source: https://github.com/maxbolgarin/lang/blob/main/README.md Functions to safely create pointers, dereference them, and provide fallback values for zero-value inputs. ```go name := lang.Ptr("John") age := lang.Ptr(25) var nilPtr *string value := lang.Deref(nilPtr) value = lang.Deref(lang.Ptr("Hi")) config := lang.Check("", "default") timeout := lang.Check(0, 30) ``` -------------------------------- ### Error Handling and Memory Management Source: https://github.com/maxbolgarin/lang/blob/main/README.md Best practices for error handling using returns instead of panics and memory management via slice copying. ```go func safeDivide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } func processLargeSlice(input []LargeStruct) []Result { relevant := lang.Filter(input, isRelevant) return lang.Convert(lang.Copy(relevant), processStruct) } ``` -------------------------------- ### Slice Operations: Reduce, Take, Skip, Flatten, Reverse (Go) Source: https://github.com/maxbolgarin/lang/blob/main/README.md Demonstrates advanced slice manipulation functions like Reduce (fold), Take, Skip, Flatten, and Reverse. These functions operate on slices to perform common data transformations. ```go // Reduce (fold) operation sum := lang.Reduce([]int{1, 2, 3, 4, 5}, 0, func(acc, n int) int { return acc + n }) // sum: 15 // Take and skip first3 := lang.Take([]int{1, 2, 3, 4, 5}, 3) // [1, 2, 3] after2 := lang.Skip([]int{1, 2, 3, 4, 5}, 2) // [3, 4, 5] // Flatten nested slices nested := [][]int{{1, 2}, {3, 4}, {5, 6}} flat := lang.Flatten(nested) // [1, 2, 3, 4, 5, 6] // Reverse reversed := lang.Reverse([]int{1, 2, 3, 4, 5}) // [5, 4, 3, 2, 1] ``` -------------------------------- ### Panic Recovery and Error Handling Utilities (Go) Source: https://github.com/maxbolgarin/lang/blob/main/README.md Provides robust error handling mechanisms, including automatic goroutine recovery with restart, function-level panic recovery converted to errors, and default value assignment on panic. It also includes utilities for wrapping errors with context and joining multiple errors. ```go // Automatic goroutine recovery with restart logger := &MyLogger{} lang.Go(logger, func() { // This goroutine will restart if it panics for { riskyOperation() time.Sleep(time.Second) } }) // Function-level panic recovery func riskyFunction() (err error) { defer func() { if lang.RecoverWithErr(&err) { // Panic was converted to error } }() // Code that might panic return nil } // Default value on panic result := lang.DefaultIfPanic("safe default", func() string { return mightPanicFunction() }) // Wrap errors with context err := someOperation() if err != nil { return lang.Wrap(err, "failed to perform operation") } // Combine multiple errors err1 := operation1() err2 := operation2() if combinedErr := lang.JoinErrors(err1, err2); combinedErr != nil { return combinedErr } ``` -------------------------------- ### Data Processing Pipeline in Go Source: https://github.com/maxbolgarin/lang/blob/main/README.md Demonstrates how to transform, filter, and group raw user data into structured profiles using the Lang library's functional primitives. ```go func processUserData(rawData []map[string]interface{}) []UserProfile { users := lang.Convert(rawData, func(raw map[string]interface{}) User { return User{ ID: lang.Type[int](raw["id"]), Name: lang.Type[string](raw["name"]), Email: lang.Type[string](raw["email"]), Age: lang.Type[int](raw["age"]), } }) validUsers := lang.Filter(users, func(u User) bool { return u.ID > 0 && u.Name != "" && strings.Contains(u.Email, "@") }) byAgeGroup := lang.GroupBy(validUsers, func(u User) string { switch { case u.Age < 18: return "minor" case u.Age < 65: return "adult" default: return "senior" } }) profiles := lang.ConvertFromMap(byAgeGroup, func(group string, users []User) UserProfile { return UserProfile{ AgeGroup: group, Count: len(users), Users: users, } }) return profiles } ``` -------------------------------- ### String Operations Source: https://github.com/maxbolgarin/lang/blob/main/README.md Tools for converting types to strings, truncating text with ellipsis, and path manipulation. ```go text := lang.String(12345) short := lang.String("Hello World", 5) truncated := lang.TruncateString("Long text here", 8, "...") path := lang.GetWithSep("config", '/') ``` -------------------------------- ### Slice Slicing with Take and Skip Source: https://context7.com/maxbolgarin/lang/llms.txt Take returns the first n elements of a slice, while Skip returns elements after the first n. These are useful for pagination and partial data processing. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} first3 := lang.Take(numbers, 3) fmt.Println(first3) // [1 2 3] rest := lang.Skip(numbers, 3) fmt.Println(rest) // [4 5 6 7 8 9 10] pageSize := 3 page2 := lang.Take(lang.Skip(numbers, pageSize), pageSize) fmt.Println(page2) // [4 5 6] } ``` -------------------------------- ### Slice Search and Analysis Source: https://github.com/maxbolgarin/lang/blob/main/README.md Utilities for finding elements, checking conditions across collections, and locating indices. ```go first, found := lang.FindFirst(numbers, func(n int) bool { return n > 5 }) allPositive := lang.All(numbers, func(n int) bool { return n > 0 }) hasEven := lang.Any(numbers, func(n int) bool { return n%2 == 0 }) index := lang.IndexOf([]string{"a", "b", "c", "b"}, "b") ``` -------------------------------- ### Traditional Go Collection Operations Source: https://github.com/maxbolgarin/lang/blob/main/README.md Demonstrates standard Go implementations for filtering, mapping, and grouping elements within collections using explicit loops and conditional statements. This approach is verbose and less declarative. ```go // Filtering var evens []int for _, n := range numbers { if n%2 == 0 { evens = append(evens, n) } } // Mapping var doubled []int for _, n := range numbers { doubled = append(doubled, n*2) } // Grouping groups := make(map[string][]Person) for _, person := range people { key := person.Department groups[key] = append(groups[key], person) } ``` -------------------------------- ### Type Conversion, Retry, and Timeout Mechanisms (Go) Source: https://github.com/maxbolgarin/lang/blob/main/README.md Details type-safe conversion utilities, a flexible retry mechanism for operations that might fail transiently, and a timeout wrapper for operations that should not exceed a specified duration. These functions enhance code reliability and control. ```go // Safe type conversion var value any = "hello" str := lang.Type[string](value) // "hello" num := lang.Type[int](value) // 0 (zero value, conversion failed) // Retry mechanism result, err := lang.Retry(3, func() (string, error) { return callExternalAPI() }) // Timeout handling result, err := lang.RunWithTimeout(5*time.Second, func() (string, error) { return longRunningOperation() }) ``` -------------------------------- ### Functional Go Collection Operations with lang Source: https://github.com/maxbolgarin/lang/blob/main/README.md Illustrates how the 'lang' library simplifies collection operations in Go using a functional style. It provides higher-order functions for filtering, mapping, and grouping, leading to more readable and maintainable code. ```go // Filtering evens := lang.Filter(numbers, func(n int) bool { return n%2 == 0 }) // Mapping doubled := lang.Map(numbers, func(n int) int { return n * 2 }) // Grouping groups := lang.GroupBy(people, func(p Person) string { return p.Department }) ``` -------------------------------- ### Convert values to string with lang.String Source: https://context7.com/maxbolgarin/lang/llms.txt Converts any input value into its string representation. Supports an optional length limit parameter and provides a shorthand alias 'S'. ```go package main import ( "fmt" "time" "github.com/maxbolgarin/lang" ) func main() { s1 := lang.String("Hello") s2 := lang.String(12345) s3 := lang.String(3.14159) s4 := lang.String(true) s5 := lang.String(time.Now()) s6 := lang.String([]byte("bytes")) long := "Hello, World!" short := lang.String(long, 5) quick := lang.S(42) fmt.Println(s1, s2, s3, s4, short, quick) } ``` -------------------------------- ### ZipToMap - Create Map from Two Slices Source: https://context7.com/maxbolgarin/lang/llms.txt Creates a map by pairing elements from two slices. If lengths differ, it uses the length of the shorter slice. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { keys := []string{"name", "age", "city"} values := []string{"John", "25", "NYC"} mapping := lang.ZipToMap(keys, values) fmt.Println(mapping) // map[age:25 city:NYC name:John] ids := []int{1, 2, 3, 4, 5} names := []string{"Alice", "Bob", "Charlie"} result := lang.ZipToMap(ids, names) fmt.Println(result) // map[1:Alice 2:Bob 3:Charlie] } ``` -------------------------------- ### Execute If Non-Zero with IfV Source: https://context7.com/maxbolgarin/lang/llms.txt Executes a function if the provided value is not the zero value. Supports an optional else function for when the value is zero. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { userID := 123 lang.IfV(userID, func() { fmt.Printf("Processing user %d\n", userID) }) var missingID int lang.IfV(missingID, func() { fmt.Println("User found") }, func() { fmt.Println("No user ID provided") }, ) } ``` -------------------------------- ### Slice Transformation and Filtering Source: https://github.com/maxbolgarin/lang/blob/main/README.md Functions for mapping, filtering, and converting slices with optional error handling support. ```go numbers := []int{1, 2, 3, 4, 5} strings := lang.Convert(numbers, func(n int) string { return fmt.Sprintf("#%d", n) }) activeAdults := lang.Filter(users, func(u User) bool { return u.Age >= 18 && u.Active }) numbers, err := lang.ConvertWithErr(inputs, func(s string) (int, error) { return strconv.Atoi(s) }) ``` -------------------------------- ### Wrap - Add Context to Errors Source: https://context7.com/maxbolgarin/lang/llms.txt Wraps an existing error with a descriptive context message. Returns nil if the input error is nil. ```go package main import ( "errors" "fmt" "github.com/maxbolgarin/lang" ) func main() { originalErr := errors.New("connection refused") wrappedErr := lang.Wrap(originalErr, "failed to connect to database") fmt.Println(wrappedErr) var noErr error result := lang.Wrap(noErr, "this won't appear") fmt.Println(result == nil) fmt.Println(errors.Is(wrappedErr, originalErr)) } ``` -------------------------------- ### Partition Slices by Predicate Source: https://context7.com/maxbolgarin/lang/llms.txt Splits a slice into two separate slices based on a boolean predicate function. It is useful for categorizing data into two groups. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} evens, odds := lang.Partition(numbers, func(n int) bool { return n%2 == 0 }) fmt.Println("Evens:", evens) fmt.Println("Odds:", odds) } ``` -------------------------------- ### Predicate Checks with All and Any Source: https://context7.com/maxbolgarin/lang/llms.txt All returns true if every element satisfies the predicate. Any returns true if at least one element satisfies the predicate. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { numbers := []int{2, 4, 6, 8, 10} allEven := lang.All(numbers, func(n int) bool { return n%2 == 0 }) anyGreaterThan5 := lang.Any(numbers, func(n int) bool { return n > 5 }) } ``` -------------------------------- ### CopyMap - Shallow Copy Map Source: https://context7.com/maxbolgarin/lang/llms.txt Creates a shallow copy of a map, ensuring that modifications to the original map do not affect the copy. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { original := map[string]int{"a": 1, "b": 2} copied := lang.CopyMap(original) original["a"] = 99 original["c"] = 3 fmt.Println("Original:", original) fmt.Println("Copied:", copied) } ``` -------------------------------- ### Recover - Basic Panic Recovery Source: https://context7.com/maxbolgarin/lang/llms.txt Defers a recovery function to catch panics within a scope, logging the event via a provided logger interface. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) type SimpleLogger struct{} func (l *SimpleLogger) Error(msg string, args ...any) { fmt.Printf("Panic recovered: %v\n", args) } func riskyOperation(logger *SimpleLogger) { defer lang.Recover(logger) var slice []int _ = slice[10] } func main() { logger := &SimpleLogger{} riskyOperation(logger) fmt.Println("Program continues after panic") } ``` -------------------------------- ### Map Grouping and Merging (Go) Source: https://github.com/maxbolgarin/lang/blob/main/README.md Details functions for grouping map entries by a specified key and merging multiple maps into a single one. GroupBy categorizes elements, while MergeMap combines maps, resolving key conflicts by taking the value from the later map. ```go // Group by category products := []Product{ {Name: "iPhone", Category: "Electronics", Price: 999}, {Name: "iPad", Category: "Electronics", Price: 799}, {Name: "Book", Category: "Literature", Price: 25}, {Name: "Pen", Category: "Office", Price: 5}, } byCategory := lang.GroupBy(products, func(p Product) string { return p.Category }) // byCategory: map[string][]Product{ // "Electronics": [{iPhone...}, {iPad...}], // "Literature": [{Book...}], // "Office": [{Pen...}], // } // Merge multiple maps priceMap1 := map[string]int{"apple": 2, "banana": 1} priceMap2 := map[string]int{"banana": 3, "orange": 4} merged := lang.MergeMap(priceMap1, priceMap2) // merged: map[string]int{"apple": 2, "banana": 3, "orange": 4} ``` -------------------------------- ### Find first match in slice in Go Source: https://context7.com/maxbolgarin/lang/llms.txt Searches for the first element in a slice that satisfies a predicate function. Returns the found element and a boolean indicating success. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} first, found := lang.FindFirst(numbers, func(n int) bool { return n > 5 && n%2 == 0 }) fmt.Printf("Found: %v, Value: %d\n", found, first) large, found := lang.FindFirst(numbers, func(n int) bool { return n > 100 }) fmt.Printf("Found: %v, Value: %d\n", found, large) } ``` -------------------------------- ### Map Manipulation: Filter, Convert, Keys (Go) Source: https://github.com/maxbolgarin/lang/blob/main/README.md Covers essential map manipulation techniques including filtering based on a condition, transforming values, and extracting keys. These operations allow for dynamic modification and inspection of map data. ```go ages := map[string]int{"Alice": 25, "Bob": 30, "Charlie": 17} // Filter maps adults := lang.FilterMap(ages, func(name string, age int) bool { return age >= 18 }) // adults: map[string]int{"Alice": 25, "Bob": 30} // Transform values descriptions := lang.ConvertMap(ages, func(age int) string { return fmt.Sprintf("%d years old", age) }) // descriptions: map[string]string{"Alice": "25 years old", "Bob": "30 years old", "Charlie": "17 years old"} // Extract keys and values names := lang.Keys(ages) // ["Alice", "Bob", "Charlie"] adultNames := lang.KeysIf(ages, func(name string, age int) bool { return age >= 18 }) // ["Alice", "Bob"] ``` -------------------------------- ### Create Pointer to Value with Ptr Source: https://context7.com/maxbolgarin/lang/llms.txt Creates a pointer to a provided literal value. This is essential for initializing structs with pointer fields where direct address-of operators cannot be used on literals. ```go package main import "github.com/maxbolgarin/lang" func main() { name := lang.Ptr("John") age := lang.Ptr(25) active := lang.Ptr(true) config := struct { Timeout *int Debug *bool }{ Timeout: lang.Ptr(30), Debug: lang.Ptr(false), } } ``` -------------------------------- ### Split Slice into Chunks (Go) Source: https://context7.com/maxbolgarin/lang/llms.txt Splits a slice into smaller slices (chunks) of a specified size. It takes the original slice and the desired chunk size as input. This is useful for batch processing or paginating data. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { items := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // Split into chunks of 3 chunks := lang.Chunk(items, 3) fmt.Println(chunks) // [[1 2 3] [4 5 6] [7 8 9] [10]] // Useful for batch processing userIDs := []int{101, 102, 103, 104, 105} batches := lang.Chunk(userIDs, 2) for i, batch := range batches { fmt.Printf("Batch %d: %v\n", i+1, batch) } // Batch 1: [101 102] // Batch 2: [103 104] // Batch 3: [105] } ``` -------------------------------- ### Shallow Copy Slices Source: https://context7.com/maxbolgarin/lang/llms.txt Creates a shallow copy of a slice to prevent side effects when modifying the original data. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { original := []int{1, 2, 3} copied := lang.Copy(original) } ``` -------------------------------- ### Return Non-Zero Value with Check Source: https://context7.com/maxbolgarin/lang/llms.txt Returns the first argument if it is not the zero value for its type; otherwise, it returns the provided default value. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { username := "" defaultName := "guest" result := lang.Check(username, defaultName) timeout := 0 result2 := lang.Check(timeout, 30) port := 8080 result3 := lang.Check(port, 3000) fmt.Println(result, result2, result3) } ``` -------------------------------- ### Conditional Function Execution with IfF Source: https://context7.com/maxbolgarin/lang/llms.txt Executes a function based on a boolean condition. Supports an optional else function to execute if the condition is false. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { isLoggedIn := true lang.IfF(isLoggedIn, func() { fmt.Println("Welcome back!") }) hasPermission := false lang.IfF(hasPermission, func() { fmt.Println("Access granted") }, func() { fmt.Println("Access denied") }, ) } ``` -------------------------------- ### Create Map from Slice using Custom Key-Value Pairs (Go) Source: https://context7.com/maxbolgarin/lang/llms.txt The SliceToMap function creates a map by transforming each element of a slice into a key-value pair using a provided function. It takes a slice and a function that defines how to extract the key and value from each element. The output is a map where keys and values are strings. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { type User struct { ID int Name string Email string } users := []User{ {1, "Alice", "alice@example.com"}, {2, "Bob", "bob@example.com"}, {3, "Charlie", "charlie@example.com"}, } // Create map with custom key-value emailMap := lang.SliceToMap(users, func(u User) (string, string) { return u.Name, u.Email }) fmt.Println(emailMap) // map[Alice:alice@example.com Bob:bob@example.com Charlie:charlie@example.com] } ``` -------------------------------- ### Go - Goroutine with Auto-Recovery Source: https://context7.com/maxbolgarin/lang/llms.txt Executes a function in a new goroutine with automatic panic recovery. If a panic occurs, the goroutine can be restarted or handled via the provided logger. ```go package main import ( "fmt" "time" "github.com/maxbolgarin/lang" ) type SimpleLogger struct{} func (l *SimpleLogger) Error(msg string, args ...any) { fmt.Printf("ERROR: %s %v\n", msg, args) } func main() { logger := &SimpleLogger{} lang.Go(logger, func() { for i := 0; ; i++ { fmt.Printf("Working... iteration %d\n", i) time.Sleep(time.Second) if i == 2 { panic("simulated crash") } } }) time.Sleep(10 * time.Second) } ``` -------------------------------- ### Index Slice by Key using a Function (Go) Source: https://context7.com/maxbolgarin/lang/llms.txt The SliceToMapByKey function creates a map where elements of a slice are used as values, and a key is generated for each element using a provided function. It's useful for indexing slices based on a specific property of their elements. The Mapping function is an alias for this functionality. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { type User struct { ID int Name string } users := []User{{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}} usersByID := lang.SliceToMapByKey(users, func(u User) int { return u.ID }) fmt.Println(usersByID[2]) // {2 Bob} // Mapping is an alias byName := lang.Mapping(users, func(u User) string { return u.Name }) fmt.Println(byName["Alice"]) } ``` -------------------------------- ### Execute functions with timeouts using lang.RunWithTimeout Source: https://context7.com/maxbolgarin/lang/llms.txt Runs a function within a specified time duration. Returns an ErrTimeout if the function execution exceeds the provided timeout period. ```go package main import ( "fmt" "time" "github.com/maxbolgarin/lang" ) func main() { result, err := lang.RunWithTimeout(2*time.Second, func() (string, error) { time.Sleep(100 * time.Millisecond) return "completed", nil }) fmt.Println(result, err) result, err = lang.RunWithTimeout(100*time.Millisecond, func() (string, error) { time.Sleep(1 * time.Second) return "never reached", nil }) if err == lang.ErrTimeout { fmt.Println("Operation timed out") } } ``` -------------------------------- ### Dereference or Default with CheckPtr Source: https://context7.com/maxbolgarin/lang/llms.txt Safely dereferences a pointer if it is not nil, returning the value. If the pointer is nil, it returns the provided default value. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { defaultValue := "default" var nilPtr *string result := lang.CheckPtr(nilPtr, defaultValue) customValue := "custom" result2 := lang.CheckPtr(&customValue, defaultValue) empty := "" result3 := lang.CheckPtr(&empty, defaultValue) fmt.Println(result, result2, result3) } ``` -------------------------------- ### AppendIfAll and AppendIfAny: Conditional Slice Appending in Go Source: https://context7.com/maxbolgarin/lang/llms.txt Offers conditional appending to slices in Go. `AppendIfAll` appends only if all provided values are non-zero, while `AppendIfAny` appends any non-zero values. These utilities are from the `github.com/maxbolgarin/lang` package and help manage slice modifications based on data validity. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { base := []string{"a", "b"} // AppendIfAll - only appends if ALL values are non-zero result := lang.AppendIfAll(base, "c", "d") fmt.Println(result) // [a b c d] result = lang.AppendIfAll(base, "c", "") fmt.Println(result) // [a b] - nothing appended because "" is zero // AppendIfAny - appends non-zero values result = lang.AppendIfAny(base, "c", "", "d", "") fmt.Println(result) // [a b c d] - empty strings filtered out } ``` -------------------------------- ### Conditional Operations Source: https://github.com/maxbolgarin/lang/blob/main/README.md Utilities for executing logic or returning values based on boolean conditions without explicit if-else blocks. ```go message := lang.If(user.IsAdmin, "Admin Panel", "User Panel") lang.IfF(user.IsLoggedIn, func() { log.Println("User logged in") }, func() { log.Println("Anonymous user") }) lang.IfV(user.ID, func() { updateUserStats(user.ID) }) ``` -------------------------------- ### Execute functions with retry logic using lang.Retry Source: https://context7.com/maxbolgarin/lang/llms.txt Repeatedly executes a function until it returns no error or the maximum number of attempts is reached. Useful for handling transient failures. ```go package main import ( "errors" "fmt" "math/rand" "github.com/maxbolgarin/lang" ) func main() { attempts := 0 result, err := lang.Retry(5, func() (string, error) { attempts++ if rand.Float32() < 0.7 { return "", errors.New("temporary failure") } return "success", nil }) if err != nil { fmt.Printf("Failed after %d attempts: %v\n", attempts, err) } else { fmt.Printf("Succeeded after %d attempts: %s\n", attempts, result) } } ``` -------------------------------- ### API Response Processing in Go Source: https://github.com/maxbolgarin/lang/blob/main/README.md Handles API response filtering and transformation with error propagation and duplicate removal. ```go func processAPIResponse(responses []APIResponse) ([]ProcessedData, error) { successful := lang.Filter(responses, func(r APIResponse) bool { return r.Status == "success" }) data, err := lang.ConvertWithErr(successful, func(r APIResponse) (ProcessedData, error) { return ProcessedData{ ID: r.ID, Value: r.Data.Value, Timestamp: time.Now(), }, nil }) if err != nil { return nil, lang.Wrap(err, "failed to process API responses") } return lang.Distinct(data), nil } ``` -------------------------------- ### Remove Zero Values with WithoutEmpty Source: https://context7.com/maxbolgarin/lang/llms.txt Filters out zero values (empty strings, zero integers) from a slice. NotEmpty is provided as an alias. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { strings := []string{"hello", "", "world"} nonEmpty := lang.WithoutEmpty(strings) fmt.Println(nonEmpty) // [hello world] } ``` -------------------------------- ### DefaultIfPanic: Fallback Value on Panic in Go Source: https://context7.com/maxbolgarin/lang/llms.txt Executes a provided function and returns a specified default value if the function panics. This is useful for providing sensible fallbacks for operations that might fail unexpectedly. It requires the `github.com/maxbolgarin/lang` package. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { // Function that panics result := lang.DefaultIfPanic("default value", func() string { panic("error!") return "never reached" }) fmt.Println(result) // "default value" // Function that succeeds result = lang.DefaultIfPanic("default", func() string { return "actual value" }) fmt.Println(result) // "actual value" // Useful for risky operations config := lang.DefaultIfPanic(map[string]string{"port": "8080"}, func() map[string]string { return loadConfigFromFile() // might panic }) fmt.Println(config) } func loadConfigFromFile() map[string]string { panic("file not found") } ``` -------------------------------- ### Create Map from Alternating Key-Value Pairs (Go) Source: https://context7.com/maxbolgarin/lang/llms.txt The PairsToMap function converts a slice of strings, where elements alternate between keys and values, into a map. It processes the slice in pairs, ignoring the last element if the slice has an odd number of elements. This is convenient for configuration-like data. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { pairs := []string{"name", "John", "age", "25", "city", "NYC"} config := lang.PairsToMap(pairs) fmt.Println(config) // map[age:25 city:NYC name:John] // Odd-length slice - last element ignored oddPairs := []string{"a", "1", "b", "2", "c"} result := lang.PairsToMap(oddPairs) fmt.Println(result) // map[a:1 b:2] } ``` -------------------------------- ### Extract Map Keys, Values, or Conditional Keys (Go) Source: https://context7.com/maxbolgarin/lang/llms.txt The Keys and Values functions extract all keys or all values from a map into separate slices, respectively. The order of elements in the returned slices is not guaranteed. KeysIf provides a way to extract keys based on a condition applied to key-value pairs. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { config := map[string]int{"timeout": 30, "retries": 3, "port": 8080} keys := lang.Keys(config) fmt.Println("Keys:", keys) // Keys: [timeout retries port] (order may vary) values := lang.Values(config) fmt.Println("Values:", values) // Values: [30 3 8080] (order may vary) // Conditional keys ages := map[string]int{"Alice": 25, "Bob": 17, "Charlie": 30} adultNames := lang.KeysIf(ages, func(name string, age int) bool { return age >= 18 }) fmt.Println("Adults:", adultNames) // Adults: [Alice Charlie] } ``` -------------------------------- ### Ensure path separators with lang.GetWithSep Source: https://context7.com/maxbolgarin/lang/llms.txt Appends a separator character to a string if it is not already present at the end. Returns the original string if the separator exists or if the input is empty. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { path1 := lang.GetWithSep("config", '/') path2 := lang.GetWithSep("config/", '/') path3 := lang.GetWithSep("api/v1", '/') empty := lang.GetWithSep("", '/') fmt.Println(path1, path2, path3, empty) } ``` -------------------------------- ### Slice Data Manipulation Source: https://github.com/maxbolgarin/lang/blob/main/README.md Advanced slice operations including deduplication, set theory (union, intersection, difference), chunking, and partitioning. ```go unique := lang.Distinct([]int{1, 2, 2, 3, 1, 4}) intersection := lang.Intersect(set1, set2) union := lang.Union(set1, set2) difference := lang.Difference(set1, set2) chunks := lang.Chunk([]int{1, 2, 3, 4, 5, 6, 7}, 3) evens, odds := lang.Partition([]int{1, 2, 3, 4, 5}, func(n int) bool { return n%2 == 0 }) ``` -------------------------------- ### RecoverWithHandler: Custom Panic Handler in Go Source: https://context7.com/maxbolgarin/lang/llms.txt Recovers from panics and executes a custom handler function with the panic value. This allows for specific actions like logging or alerting when a panic occurs. It depends on the `github.com/maxbolgarin/lang` package. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func riskyOperation() { defer lang.RecoverWithHandler(func(panicValue any) { fmt.Printf("Custom handler: caught panic with value: %v\n", panicValue) // Log to external service, send alert, etc. }) panic("critical error") } func main() { riskyOperation() fmt.Println("Execution continues") } ``` -------------------------------- ### CheckIndex and Index: Safe Slice Access in Go Source: https://context7.com/maxbolgarin/lang/llms.txt Provides safe methods for accessing slice elements in Go, preventing panics due to out-of-bounds indices. `CheckIndex` returns the element and a boolean indicating success, while `Index` returns the element or its zero value. These functions are part of the `github.com/maxbolgarin/lang` package. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { items := []string{"a", "b", "c"} // CheckIndex returns value and boolean val, ok := lang.CheckIndex(items, 1) fmt.Printf("Value: %s, Found: %v\n", val, ok) // Value: b, Found: true val, ok = lang.CheckIndex(items, 10) fmt.Printf("Value: %s, Found: %v\n", val, ok) // Value: , Found: false // Index returns just the value (or zero value) first := lang.Index(items, 0) fmt.Println(first) // "a" outOfBounds := lang.Index(items, 100) fmt.Println(outOfBounds) // "" (empty string) // First returns the first element head := lang.First(items) fmt.Println(head) // "a" } ``` -------------------------------- ### Convert Map to Slice of Transformed Elements (Go) Source: https://context7.com/maxbolgarin/lang/llms.txt The ConvertFromMap function transforms each key-value pair of a map into an element of a slice using a provided function. The function receives the key and value and returns the transformed element. This is useful for serializing map data or creating formatted string representations. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { ages := map[string]int{"Alice": 25, "Bob": 30, "Charlie": 35} descriptions := lang.ConvertFromMap(ages, func(name string, age int) string { return fmt.Sprintf("%s is %d years old", name, age) }) for _, desc := range descriptions { fmt.Println(desc) } // Alice is 25 years old // Bob is 30 years old // Charlie is 35 years old } ``` -------------------------------- ### MergeMap - Merge Multiple Maps Source: https://context7.com/maxbolgarin/lang/llms.txt Merges multiple maps into a single map. Later values overwrite earlier ones if keys collide. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { defaults := map[string]int{"timeout": 30, "retries": 3} overrides := map[string]int{"timeout": 60, "port": 8080} merged := lang.MergeMap(defaults, overrides) fmt.Println(merged) // map[port:8080 retries:3 timeout:60] config := lang.MergeMap( map[string]string{"env": "dev"}, map[string]string{"db": "postgres"}, map[string]string{"env": "prod"}, ) fmt.Println(config) // map[db:postgres env:prod] } ``` -------------------------------- ### Set Union of Slices (Go) Source: https://context7.com/maxbolgarin/lang/llms.txt Returns a new slice containing unique elements from all input slices. It accepts multiple slices and combines them into a single slice with no duplicates. The order of elements is preserved from the input slices. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { set1 := []int{1, 2, 3} set2 := []int{3, 4, 5} set3 := []int{5, 6, 7} all := lang.Union(set1, set2, set3) fmt.Println(all) // [1 2 3 4 5 6 7] // Combine multiple tag lists tags := lang.Union( []string{"go", "backend"}, []string{"docker", "go"}, []string{"kubernetes", "backend"}, ) fmt.Println(tags) // [go backend docker kubernetes] } ``` -------------------------------- ### Map slice elements in Go Source: https://context7.com/maxbolgarin/lang/llms.txt Transforms each element of a slice into a new value of the same type using a mapping function. Useful for applying operations like mathematical calculations or string formatting to every item. ```go package main import ( "fmt" "strings" "github.com/maxbolgarin/lang" ) func main() { numbers := []int{1, 2, 3, 4, 5} doubled := lang.Map(numbers, func(n int) int { return n * 2 }) fmt.Println(doubled) words := []string{"hello", "world", "go"} upper := lang.Map(words, func(s string) string { return strings.ToUpper(s) }) fmt.Println(upper) } ``` -------------------------------- ### Reverse Slice Order (Go) Source: https://context7.com/maxbolgarin/lang/llms.txt Returns a new slice with the elements in reverse order. The original slice remains unchanged. This function is useful when the order of elements needs to be inverted. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { numbers := []int{1, 2, 3, 4, 5} reversed := lang.Reverse(numbers) fmt.Println(reversed) // [5 4 3 2 1] // Original unchanged fmt.Println(numbers) // [1 2 3 4 5] words := []string{"first", "second", "third"} reversedWords := lang.Reverse(words) fmt.Println(reversedWords) // [third second first] } ``` -------------------------------- ### RecoverWithErr: Convert Panic to Error in Go Source: https://context7.com/maxbolgarin/lang/llms.txt Recovers from panics within a function and converts them into a Go error. This is useful for handling unexpected panics gracefully and returning them as standard errors. It requires the `github.com/maxbolgarin/lang` package. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func riskyOperation() (result string, err error) { defer lang.RecoverWithErr(&err) // Code that might panic panic("something went wrong") return "success", nil } func main() { result, err := riskyOperation() if err != nil { fmt.Printf("Operation failed: %v\n", err) // Output: Operation failed: something went wrong } else { fmt.Printf("Result: %s\n", result) } } ``` -------------------------------- ### Set Difference of Slices (Go) Source: https://context7.com/maxbolgarin/lang/llms.txt Returns a new slice containing elements that are present in the first slice but not in the second. It takes two slices and returns the difference. This is useful for finding new or remaining items after comparison. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { all := []int{1, 2, 3, 4, 5} excluded := []int{2, 4} remaining := lang.Difference(all, excluded) fmt.Println(remaining) // [1 3 5] // Find new items oldList := []string{"apple", "banana"} newList := []string{"apple", "banana", "cherry", "date"} newItems := lang.Difference(newList, oldList) fmt.Println(newItems) // [cherry date] } ``` -------------------------------- ### Safe Pointer Dereferencing with Deref Source: https://context7.com/maxbolgarin/lang/llms.txt Safely retrieves the value from a pointer. If the pointer is nil, it returns the zero value for the underlying type, preventing nil pointer panics. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { var nilPtr *string value := lang.Deref(nilPtr) name := "Alice" value = lang.Deref(&name) var nilInt *int num := lang.Deref(nilInt) fmt.Println(value, num) } ``` -------------------------------- ### Ternary Conditional with If Source: https://context7.com/maxbolgarin/lang/llms.txt Provides a functional ternary operator. It returns the second argument if the boolean condition is true, otherwise it returns the third argument. ```go package main import ( "fmt" "github.com/maxbolgarin/lang" ) func main() { isAdmin := true message := lang.If(isAdmin, "Admin Panel", "User Panel") age := 17 status := lang.If(age >= 18, "adult", "minor") count := 5 plural := lang.If(count == 1, "item", "items") fmt.Printf("%s, %s, %d %s\n", message, status, count, plural) } ```