============================================================================ Search and Predicate Functions ============================================================================
()
| 122 | // ============================================================================ |
| 123 | |
| 124 | func demonstrateSearch() { |
| 125 | fmt.Println("\n=== Search & Predicate Functions ===") |
| 126 | |
| 127 | products := []Product{ |
| 128 | {1, "Laptop", 999.99, "Electronics", true}, |
| 129 | {2, "Mouse", 29.99, "Electronics", true}, |
| 130 | {3, "Keyboard", 79.99, "Electronics", false}, |
| 131 | {4, "Desk", 299.99, "Furniture", true}, |
| 132 | {5, "Chair", 199.99, "Furniture", true}, |
| 133 | } |
| 134 | |
| 135 | // Find: First matching element (returns Option) |
| 136 | // Using method-based API (match Option bug workaround) |
| 137 | found := dgo.Find(products, func(p Product) bool { return p.Price > 500 }) |
| 138 | if found.IsSome() { |
| 139 | p := found.Unwrap() |
| 140 | fmt.Printf("Found expensive item: %s ($%.2f)\n", p.Name, p.Price) |
| 141 | } else { |
| 142 | fmt.Println("No expensive items found") |
| 143 | } |
| 144 | |
| 145 | // FindIndex: Index of first match |
| 146 | idx := dgo.FindIndex(products, func(p Product) bool { return p.Category == "Furniture" }) |
| 147 | if idx.IsSome() { |
| 148 | fmt.Printf("First furniture at index: %d\n", idx.Unwrap()) |
| 149 | } else { |
| 150 | fmt.Println("No furniture found") |
| 151 | } |
| 152 | |
| 153 | // Any: Check if any element matches |
| 154 | hasOutOfStock := dgo.Any(products, func(p Product) bool { return !p.InStock }) |
| 155 | fmt.Printf("Has out of stock items: %v\n", hasOutOfStock) |
| 156 | |
| 157 | // All: Check if all elements match |
| 158 | allInStock := dgo.All(products, func(p Product) bool { return p.InStock }) |
| 159 | fmt.Printf("All items in stock: %v\n", allInStock) |
| 160 | |
| 161 | // NoneMatch: Check if no elements match |
| 162 | noExpensive := dgo.NoneMatch(products, func(p Product) bool { return p.Price > 2000 }) |
| 163 | fmt.Printf("No items over $2000: %v\n", noExpensive) |
| 164 | |
| 165 | // Contains: Check for value (comparable types) |
| 166 | numbers := []int{10, 20, 30, 40, 50} |
| 167 | has30 := dgo.Contains(numbers, 30) |
| 168 | fmt.Printf("Contains 30: %v\n", has30) |
| 169 | |
| 170 | // Count: Count matching elements |
| 171 | electronicsCount := dgo.Count(products, func(p Product) bool { return p.Category == "Electronics" }) |
| 172 | fmt.Printf("Electronics count: %d\n", electronicsCount) |
| 173 | } |
| 174 | |
| 175 | // ============================================================================ |
| 176 | // Advanced Functions |