docs(phrasebook,sieve,towel,wire,wristband): compile README Go examples via src= (quick-261118-qsd)

This commit is contained in:
Jakub Zych
2026-11-18 20:01:05 +01:00
parent c517db564c
commit 6409837b0c
12 changed files with 509 additions and 148 deletions

View File

@@ -124,3 +124,59 @@ func ExampleSet_Slice() {
fmt.Println(ids)
// Output: [1 2 3]
}
// blogPost is the model that shape filters, groups and reshapes.
type blogPost struct {
ID int
Author string
Title string
Published bool
}
// postResponse is the JSON shape of one post in a list response.
type postResponse struct {
ID int `json:"id"`
Title string `json:"title"`
}
func shape(posts []blogPost, rawIDs []string) error {
// Keep the published posts and turn them into response structs.
published := sieve.Filter(posts, func(p blogPost) bool { return p.Published })
body := sieve.Map(published, func(p blogPost) postResponse {
return postResponse{ID: p.ID, Title: p.Title}
})
// Key by ID for lookups, group by author, keep one post per author.
byID := sieve.KeyBy(posts, func(p blogPost) int { return p.ID })
byAuthor := sieve.GroupBy(posts, func(p blogPost) string { return p.Author })
firstPerAuthor := sieve.UniqBy(posts, func(p blogPost) string { return p.Author })
// Split drafts from published posts, and find the first draft.
live, drafts := sieve.Partition(posts, func(p blogPost) bool { return p.Published })
firstDraft, found := sieve.Find(posts, func(p blogPost) bool { return !p.Published })
// Parse IDs from a query string, stopping at the first bad one.
ids, err := sieve.TryMap(rawIDs, strconv.Atoi)
if err != nil {
return fmt.Errorf("blog: bad post id: %w", err)
}
wanted := sieve.SetOf(ids...)
fmt.Println(len(body), len(byID), len(byAuthor), len(firstPerAuthor),
len(live), len(drafts), firstDraft.Title, found, wanted.Has(1))
return nil
}
func Example_shape() {
posts := []blogPost{
{ID: 1, Author: "ana", Title: "Hello", Published: true},
{ID: 2, Author: "bob", Title: "Summer"},
{ID: 3, Author: "ana", Title: "Goodbye", Published: true},
}
fmt.Println(shape(posts, []string{"1", "3"}))
fmt.Println(shape(posts, []string{"1", "x"}))
// Output:
// 2 3 2 2 2 1 Summer true true
// <nil>
// blog: bad post id: strconv.Atoi: parsing "x": invalid syntax
}