〰️

実アプリケーションにおけるsamber/lo使用例

2024/09/27に公開

この記事でわかること

samber/loは便利。

概要

samber/loはsliceを操作するときに便利な関数を集めたgolangのライブラリです。
スクリプト言語でよく出てくるfilter, mapなどが実装されています。

JavaScriptのlodashをgolangに置き換えたものなので、lodashを使っている人はあまり違和感なく使えると思います。
Lisp,Rubyあたりに慣れている人も便利に使えるかと思います。

例たち

気付いたら追加します。

元データ

// 商品データの構造体
type Product struct {
	ID          int
	Name        string
	Price       float64
	Category    string
	Description string
}
// 商品データのサンプル
products := []Product{
    {ID: 1, Name: "Apple", Price: 1.00, Category: "Fruit", Description: "A sweet and juicy apple"},
    {ID: 2, Name: "Banana", Price: 0.50, Category: "Fruit", Description: "A yellow and curved banana"},
    {ID: 3, Name: "Milk", Price: 2.50, Category: "Dairy", Description: "Fresh cow's milk"},
    {ID: 4, Name: "Bread", Price: 1.50, Category: "Bakery", Description: "A soft and crusty bread"},
    {ID: 5, Name: "Cheese", Price: 3.00, Category: "Dairy", Description: "A sharp cheddar cheese"},

idだけの配列を作る

lo.Map(products, func(p Product, _ int) int { return p.ID })

カテゴリが "Fruit" の商品を抽出

	fruitProducts := lo.Filter(products, func(p Product, _ int) bool {
		return p.Category == "Fruit"
	})
	fmt.Println("Fruit Products:", fruitProducts)

商品の価格を 10% 割引

	discountedProducts := lo.Map(products, func(p Product, _ int) Product {
		return Product{
			ID:          p.ID,
			Name:        p.Name,
			Price:       p.Price * 0.9, // 10% 割引
			Category:    p.Category,
			Description: p.Description,
		}
	})
	fmt.Println("Discounted Products:", discountedProducts)

全商品価格の合計を計算

	totalPrice := lo.Reduce(products, func(acc float64, p Product, _ int) float64 {
		return acc + p.Price
	}, 0)
	fmt.Println("Total Price:", totalPrice)

最も高価な商品を抽出

	mostExpensiveProduct := lo.MaxBy(products, func(p1, p2 Product) bool {
		return p1.Price > p2.Price
	})
	fmt.Println("Most Expensive Product:", mostExpensiveProduct)

idをキーのmapにする

	productMap := lo.Associate(products, func(p Product) (int, Product) {
		return p.ID, p
	})
	fmt.Println("Product Map:", productMap)

Discussion