feat: fail fast if a lat/lng is not found

Stop the search if the first 5 timezone objects found by the index
do not contain the input lat/lng thus saving computing resources
This commit is contained in:
Andrea Giacobino
2024-06-25 23:10:23 +02:00
parent a194645141
commit 37cff76214
2 changed files with 11 additions and 7 deletions

View File

@@ -65,11 +65,17 @@ func NewGeo2TzRTreeIndexFromGeoJSON(geoJSONPath string) (*Geo2TzRTreeIndex, erro
// if the timezone is not found, it returns an error
// It first searches in the land index, if not found, it searches in the sea index
func (g *Geo2TzRTreeIndex) Lookup(lat, lng float64) (tzID string, err error) {
chances := 5
// search the land index
g.land.Search(
[2]float64{lat, lng},
[2]float64{lat, lng},
func(min, max [2]float64, data timezoneGeo) bool {
chances--
if chances == 0 {
return false
}
for _, p := range data.Polygons {
if isPointInPolygonPIP(vertex{lat, lng}, p) {
tzID = data.Name
@@ -82,10 +88,15 @@ func (g *Geo2TzRTreeIndex) Lookup(lat, lng float64) (tzID string, err error) {
if tzID == "" {
// if not found, search the sea index
chances = 5
g.sea.Search(
[2]float64{lat, lng},
[2]float64{lat, lng},
func(min, max [2]float64, data timezoneGeo) bool {
chances--
if chances == 0 {
return false
}
for _, p := range data.Polygons {
if isPointInPolygonPIP(vertex{lat, lng}, p) {
tzID = data.Name

View File

@@ -190,13 +190,6 @@ func Test_TzRequest(t *testing.T) {
http.StatusOK,
`{"coords":{"lat":51.477811,"lon":0},"tz":"Europe/London"}`,
},
{
"PASS: valid coordinates",
"43.42582",
"11.831443",
http.StatusOK,
`{"coords":{"lat":43.42582,"lon":11.831443},"tz":"Europe/Rome"}`,
},
{
"PASS: valid coordinates",
"41.9028",