-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.go
56 lines (48 loc) · 948 Bytes
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"errors"
"fmt"
)
type Listable interface {
Title() string
Len() int
Render(int) string
}
type Selectable interface {
Listable
Selection() string
}
func choose(s Selectable) (selectedIndex int, err error) {
list(s)
fmt.Print(s.Selection())
_, err = fmt.Scanf("%d\n", &selectedIndex)
selectedIndex--
if err != nil {
return
}
if selectedIndex < 0 || selectedIndex >= s.Len() {
err = errors.New("Incorrect selection.")
}
return
}
func list(s Listable) {
fmt.Printf(" %s\n", bold(s.Title()))
itemsCount := s.Len()
for i := 0; i < itemsCount; i++ {
fmt.Printf("(%-2d) %s\n", i+1, s.Render(i))
}
}
func enterText(label string) (input string, err error) {
fmt.Print(label)
_, err = fmt.Scanf("%s\n", &input)
return
}
func find(s Listable, f func(int) bool) (pos int, ok bool) {
itemsCount := s.Len()
for i := 0; i < itemsCount; i++ {
if f(i) {
return i, true
}
}
return -1, false
}