randomitems.go
This file
Path
examples/list-fancy/randomitems.go
164 lines · 2.4 KiB · Go
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than 3dfbcd9 point at it.
feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1–164why, one step back1package main23import (4 "math/rand"5 "sync"6)78type randomItemGenerator struct {9 titles []string10 descs []string11 titleIndex int12 descIndex int13 mtx *sync.Mutex14 shuffle *sync.Once15}1617func (r *randomItemGenerator) reset() {18 r.mtx = &sync.Mutex{}19 r.shuffle = &sync.Once{}2021 r.titles = []string{22 "Artichoke",23 "Baking Flour",24 "Bananas",25 "Barley",26 "Bean Sprouts",27 "Bitter Melon",28 "Black Cod",29 "Blood Orange",30 "Brown Sugar",31 "Cashew Apple",32 "Cashews",33 "Cat Food",34 "Coconut Milk",35 "Cucumber",36 "Curry Paste",37 "Currywurst",38 "Dill",39 "Dragonfruit",40 "Dried Shrimp",41 "Eggs",42 "Fish Cake",43 "Furikake",44 "Garlic",45 "Gherkin",46 "Ginger",47 "Granulated Sugar",48 "Grapefruit",49 "Green Onion",50 "Hazelnuts",51 "Heavy whipping cream",52 "Honey Dew",53 "Horseradish",54 "Jicama",55 "Kohlrabi",56 "Leeks",57 "Lentils",58 "Licorice Root",59 "Meyer Lemons",60 "Milk",61 "Molasses",62 "Muesli",63 "Nectarine",64 "Niagamo Root",65 "Nopal",66 "Nutella",67 "Oat Milk",68 "Oatmeal",69 "Olives",70 "Papaya",71 "Party Gherkin",72 "Peppers",73 "Persian Lemons",74 "Pickle",75 "Pineapple",76 "Plantains",77 "Pocky",78 "Powdered Sugar",79 "Quince",80 "Radish",81 "Ramps",82 "Star Anise",83 "Sweet Potato",84 "Tamarind",85 "Unsalted Butter",86 "Watermelon",87 "Weißwurst",88 "Yams",89 "Yeast",90 "Yuzu",91 "Snow Peas",92 }9394 r.descs = []string{95 "A little weird",96 "Bold flavor",97 "Can’t get enough",98 "Delectable",99 "Expensive",100 "Expired",101 "Exquisite",102 "Fresh",103 "Gimme",104 "In season",105 "Kind of spicy",106 "Looks fresh",107 "Looks good to me",108 "Maybe not",109 "My favorite",110 "Oh my",111 "On sale",112 "Organic",113 "Questionable",114 "Really fresh",115 "Refreshing",116 "Salty",117 "Scrumptious",118 "Delectable",119 "Slightly sweet",120 "Smells great",121 "Tasty",122 "Too ripe",123 "At last",124 "What?",125 "Wow",126 "Yum",127 "Maybe",128 "Sure, why not?",129 }130131 r.shuffle.Do(func() {132 shuf := func(x []string) {133 rand.Shuffle(len(x), func(i, j int) { x[i], x[j] = x[j], x[i] })134 }135 shuf(r.titles)136 shuf(r.descs)137 })138}139140func (r *randomItemGenerator) next() item {141 if r.mtx == nil {142 r.reset()143 }144145 r.mtx.Lock()146 defer r.mtx.Unlock()147148 i := item{149 title: r.titles[r.titleIndex],150 description: r.descs[r.descIndex],151 }152153 r.titleIndex++154 if r.titleIndex >= len(r.titles) {155 r.titleIndex = 0156 }157158 r.descIndex++159 if r.descIndex >= len(r.descs) {160 r.descIndex = 0161 }162163 return i164}