-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
81 lines (64 loc) · 1.82 KB
/
app.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package roku
import (
"sort"
"strings"
)
// App represents an app installed on the device
type App struct {
Text string `xml:",chardata"`
ID int `xml:"id,attr"`
Type string `xml:"type,attr"`
Version string `xml:"version,attr"`
}
// Apps is a slice of App
type Apps struct {
Apps []*App `xml:"app"`
}
// ActiveApp details the app that is currently active on the device
type ActiveApp struct {
App string `xml:"app"`
Screensaver struct {
Text string `xml:",chardata"`
ID int `xml:"id,attr"`
Type string `xml:"type,attr"`
Version string `xml:"version,attr"`
} `xml:"screensaver"`
}
// sort.Sort interface implementation
type sortByID Apps
func (a sortByID) Len() int { return len(a.Apps) }
func (a sortByID) Swap(i, j int) { a.Apps[i], a.Apps[j] = a.Apps[j], a.Apps[i] }
func (a sortByID) Less(i, j int) bool { return a.Apps[i].ID <= a.Apps[j].ID }
// FindById searches for an app by ID
// Returns the app and true if found
func (a *Apps) FindByID(id int) (*App, bool) {
sort.Sort(sortByID(*a))
// binary search for idx
i := sort.Search(len(a.Apps), func(i int) bool {
// >= in search
return a.Apps[i].ID >= id
})
// found
if i < len(a.Apps) && a.Apps[i].ID == id {
return a.Apps[i], true
}
return &App{}, false
}
// FindByName searches for an app by name
// Returns the app and true if found
func (a *Apps) FindByName(text string) (*App, bool) {
// sort the slice
sort.Slice(a.Apps, func(i, j int) bool {
return strings.ToLower(a.Apps[i].Text) <= strings.ToLower(a.Apps[j].Text)
})
text = strings.ToLower(text)
// binary search >=
i := sort.Search(len(a.Apps), func(i int) bool {
return strings.ToLower(a.Apps[i].Text) >= text
})
// found
if i < len(a.Apps) && strings.ToLower(a.Apps[i].Text) == text {
return a.Apps[i], true
}
return &App{}, false
}