|
| 1 | +package choice |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +func choiceStr(choice any) string { |
| 13 | + if v, ok := choice.(Description); ok { |
| 14 | + return v.Description() |
| 15 | + } else if v, ok := choice.(fmt.Stringer); ok { |
| 16 | + return v.String() |
| 17 | + } |
| 18 | + return fmt.Sprint(choice) |
| 19 | +} |
| 20 | + |
| 21 | +func Menu[E Choice](choices []E) string { |
| 22 | + var digit int |
| 23 | + for n := len(choices); n != 0; digit++ { |
| 24 | + n /= 10 |
| 25 | + } |
| 26 | + option := fmt.Sprintf("%%%dd", digit) |
| 27 | + var b strings.Builder |
| 28 | + for i, choice := range choices { |
| 29 | + fmt.Fprintf(&b, "%s. %s\n", fmt.Sprintf(option, i+1), choiceStr(choice)) |
| 30 | + } |
| 31 | + return b.String() |
| 32 | +} |
| 33 | + |
| 34 | +func choose[E Choice](choice string, choices []E) (res any, err error) { |
| 35 | + n, err := strconv.Atoi(choice) |
| 36 | + if err != nil { |
| 37 | + return nil, choiceError(choice) |
| 38 | + } |
| 39 | + if length := len(choices); n < 1 || n > length { |
| 40 | + return nil, choiceError(fmt.Sprintf("out of range(1-%d): %d", length, n)) |
| 41 | + } |
| 42 | + return choices[n-1].Run() |
| 43 | +} |
| 44 | + |
| 45 | +func Choose[E Choice](choices []E) (choice string, res any, err error) { |
| 46 | + if length := len(choices); length == 0 { |
| 47 | + return |
| 48 | + } |
| 49 | + fmt.Print(Menu(choices)) |
| 50 | + fmt.Print("\nPlease choose: ") |
| 51 | + scanner := bufio.NewScanner(os.Stdin) |
| 52 | + scanner.Scan() |
| 53 | + b := bytes.TrimSpace(scanner.Bytes()) |
| 54 | + if bytes.EqualFold(b, []byte("q")) || bytes.Contains(b, []byte{27}) { |
| 55 | + return |
| 56 | + } |
| 57 | + res, err = choose(string(b), choices) |
| 58 | + return |
| 59 | +} |
0 commit comments