forked from xyproto/wallutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
closest.go
43 lines (40 loc) · 1.18 KB
/
closest.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
package wallutils
import (
"os"
)
// Exists checks if the given filename exists in the current directory
// (or if an absolute path exists)
func Exists(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}
// Closest takes a list of filenames on the form "*_WIDTHxHEIGHT.ext".
// WIDTH and HEIGHT are numbers. Closest returns the filename that is closest
// to the average monitor resolution. Any filenames not following the pattern
// will result in an error being returned.
func Closest(filenames []string) (string, error) {
avgRes, err := AverageResolution()
if err != nil {
return "", err
}
// map: (distance to average resolution) => (filename)
d := make(map[int]string)
var dist int
var minDist int
var minDistSet bool
for _, filename := range filenames {
res, err := FilenameToRes(filename)
if err != nil {
return "", err
}
dist = Distance(avgRes, res)
if dist < minDist || !minDistSet {
minDist = dist
minDistSet = true
}
//fmt.Printf("FILENAME %s HAS DISTANCE %d TO AVERAGE RESOLUTION %s\n", filename, dist, avgRes)
d[dist] = filename
}
// ok, have a map, now find the filename of the smallest distance
return d[minDist], nil
}