Files
base/pkg/array/example_test.go
2026-04-10 18:25:21 +03:30

290 lines
7.2 KiB
Go

package array_test
import (
"errors"
"fmt"
"sort"
"strings"
"base/pkg/array"
)
// Product represents a product in an base system
type Product struct {
ID int
Name string
Price float64
Category string
}
// ProductDTO is a data transfer object for Product
type ProductDTO struct {
ID int `json:"id"`
Name string `json:"name"`
PriceUSD string `json:"price_usd"`
Available bool `json:"available"`
}
// base represents a store's base
type base struct {
StoreID int
StoreName string
Products []Product
}
// Review represents a customer review
type Review struct {
ProductID int
Rating int
Comment string
}
func Example_map() {
// Create a slice of Product structs
products := []Product{
{ID: 1, Name: "Laptop", Price: 999.99, Category: "Electronics"},
{ID: 2, Name: "Headphones", Price: 99.99, Category: "Electronics"},
{ID: 3, Name: "Keyboard", Price: 49.99, Category: "Accessories"},
}
// Use Map to transform Product structs to ProductDTO structs
productDTOs := array.Map(products, func(p Product, i int) ProductDTO {
return ProductDTO{
ID: p.ID,
Name: p.Name,
PriceUSD: fmt.Sprintf("$%.2f", p.Price),
Available: p.Price > 0,
}
})
// Print the result
for _, dto := range productDTOs {
fmt.Printf("Product %d: %s - %s\n", dto.ID, dto.Name, dto.PriceUSD)
}
// Output:
// Product 1: Laptop - $999.99
// Product 2: Headphones - $99.99
// Product 3: Keyboard - $49.99
}
func Example_mapWithError() {
// Create a slice of Product structs
products := []Product{
{ID: 1, Name: "Laptop", Price: 999.99, Category: "Electronics"},
{ID: 2, Name: "Headphones", Price: 99.99, Category: "Electronics"},
{ID: 3, Name: "Keyboard", Price: 49.99, Category: "Accessories"},
}
// Use MapWithError to transform Product structs to discounted products,
// but only if the discount can be applied
discountedProducts, err := array.MapWithError(products, func(p Product, i int) (*Product, error) {
// For this example, we'll say we can't discount items under $50
if p.Price < 50.0 {
return nil, errors.New("cannot discount items under $50")
}
// Create a new product with 10% discount
discounted := p
discounted.Price = p.Price * 0.9
return &discounted, nil
})
// Check for errors
if err != nil {
fmt.Println("Error:", err)
} else {
// Print the result
for _, p := range discountedProducts {
fmt.Printf("Discounted %s: $%.2f\n", p.Name, p.Price)
}
}
// Try with products that all meet the criteria
expensiveProducts := []Product{
{ID: 1, Name: "Laptop", Price: 999.99, Category: "Electronics"},
{ID: 2, Name: "Smartphone", Price: 699.99, Category: "Electronics"},
}
discountedProducts, err = array.MapWithError(expensiveProducts, func(p Product, i int) (*Product, error) {
// All these products can be discounted
discounted := p
discounted.Price = p.Price * 0.9
return &discounted, nil
})
// Print the successful result
if err != nil {
fmt.Println("Error:", err)
} else {
for _, p := range discountedProducts {
fmt.Printf("Discounted %s: $%.2f\n", p.Name, p.Price)
}
}
// Output:
// Error: cannot discount items under $50
// Discounted Laptop: $899.99
// Discounted Smartphone: $629.99
}
func Example_mapD() {
// Create a map of store inventories
storeInventories := map[string]base{
"NY": {
StoreID: 1,
StoreName: "New York Store",
Products: []Product{
{ID: 1, Name: "Laptop", Price: 999.99, Category: "Electronics"},
{ID: 2, Name: "Headphones", Price: 99.99, Category: "Electronics"},
},
},
"LA": {
StoreID: 2,
StoreName: "Los Angeles Store",
Products: []Product{
{ID: 1, Name: "Laptop", Price: 1099.99, Category: "Electronics"},
{ID: 3, Name: "Keyboard", Price: 49.99, Category: "Accessories"},
},
},
}
// Use MapD to extract and format store information
storeInfos := array.MapD(storeInventories, func(inv base, location string) string {
return fmt.Sprintf("%s (ID: %d) - %s - %d products",
inv.StoreName, inv.StoreID, location, len(inv.Products))
})
// Sort the results for consistent output
sort.Strings(storeInfos)
// Print the result
for _, info := range storeInfos {
fmt.Println(info)
}
// Output:
// Los Angeles Store (ID: 2) - LA - 2 products
// New York Store (ID: 1) - NY - 2 products
}
func Example_forEach() {
// Create a slice of Product structs
products := []Product{
{ID: 1, Name: "Laptop", Price: 999.99, Category: "Electronics"},
{ID: 2, Name: "Headphones", Price: 99.99, Category: "Electronics"},
{ID: 3, Name: "Keyboard", Price: 49.99, Category: "Accessories"},
}
// Use ForEach to apply a 10% discount to all products
array.ForEach(products, func(p *Product, i int) {
p.Price = p.Price * 0.9
})
// Print the result
for _, p := range products {
fmt.Printf("%s: $%.2f\n", p.Name, p.Price)
}
// Output:
// Laptop: $899.99
// Headphones: $89.99
// Keyboard: $44.99
}
func Example_mapMany() {
// Create a slice of base structs
stores := []base{
{
StoreID: 1,
StoreName: "New York Store",
Products: []Product{
{ID: 1, Name: "Laptop", Price: 999.99, Category: "Electronics"},
{ID: 2, Name: "Headphones", Price: 99.99, Category: "Electronics"},
},
},
{
StoreID: 2,
StoreName: "Los Angeles Store",
Products: []Product{
{ID: 1, Name: "Laptop", Price: 1099.99, Category: "Electronics"},
{ID: 3, Name: "Keyboard", Price: 49.99, Category: "Accessories"},
},
},
}
// Use MapMany to flatten the store inventories into a list of product information
// but only include products priced over $100
productInfos := array.MapMany(stores,
func(store base) []Product {
return store.Products
},
func(store base, product Product) *string {
if product.Price < 100 {
return nil // Skip products under $100
}
info := fmt.Sprintf("%s - %s - $%.2f",
store.StoreName, product.Name, product.Price)
return &info
})
// Sort for consistent output
sort.Strings(productInfos)
// Print the result
for _, info := range productInfos {
fmt.Println(info)
}
// Output:
// Los Angeles Store - Laptop - $1099.99
// New York Store - Laptop - $999.99
}
func Example_mapManyD() {
// Create a map of store inventories
storeInventories := map[string]base{
"NY": {
StoreID: 1,
StoreName: "New York Store",
Products: []Product{
{ID: 1, Name: "Laptop", Price: 999.99, Category: "Electronics"},
{ID: 2, Name: "Headphones", Price: 99.99, Category: "Electronics"},
},
},
"LA": {
StoreID: 2,
StoreName: "Los Angeles Store",
Products: []Product{
{ID: 1, Name: "Laptop", Price: 1099.99, Category: "Electronics"},
{ID: 3, Name: "Keyboard", Price: 49.99, Category: "Accessories"},
},
},
}
// Use MapManyD to flatten the store inventories into a list of product names
productNames := array.MapManyD(storeInventories,
func(base base) []Product {
return base.Products
},
func(product Product) string {
return strings.ToUpper(product.Name)
})
// Sort for consistent output
sort.Strings(productNames)
// Print the result
fmt.Println("All product names (uppercase):")
for _, name := range productNames {
fmt.Println(name)
}
// Output:
// All product names (uppercase):
// HEADPHONES
// KEYBOARD
// LAPTOP
// LAPTOP
}