Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add ChooseIndex, AdvancedChooseIndex, and MultiChooseIndex. #60

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

ad8-adriant
Copy link

Hi,

This PR adds variants of Choose, AdvancedChoose and MultiChoose that return the index of the selected choice(s) rather than the string value.

I've encountered a number of situations where I wanted to prompt a user to select from an existing slice of arbitrary Go values, dynamically transformed into prompt options. That initial transformation is easy enough, but things get awkward once an option is selected as only the prompt text is returned, requiring a string search of the generated options to find the index of the selected value.

The new methods remove the search step by returning the index, allowing the final result to be retrieved directly, e.g.:

// Asks the user to select an element of vals, transformed into prompt options by fn.
func ChooseFrom[VS ~[]V, V any](ask string, vals VS, fn func(V) choose.Choice) (V, error) {
  opts := make([]choose.Choice, len(vals))
  for idx, val := range vals {
    opts[idx] = fn(val)
  }
  idx, err := prompt.New().Ask(ask).AdvancedChooseIndex(opts)
  if err != nil {
    var nop V
    return nop, err
  }
  return vals[idx], err
}
type MyThing struct {
  Name string
  A, B int
}

var ts = []MyThing{
  {"First", 1, 2},
  {"Second", 3, 4},
  {"Third", 5, 6},
  {"Fourth", 7, 8},
  {"Fifth", 9, 10},
}

func main() {
  val, err := ChooseFrom("Pick a thing.", ts, func(v MyThing) choose.Choice {
    return choose.Choice{
      Text: v.Name,
      Note: fmt.Sprintf("A = %d, B = %d", v.A, v.B),
    }
  })
  if err != nil {
    panic(err)
  }
  fmt.Println(val)
}

choosefrom

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant