Skip to content

Commit

Permalink
feat: fail fast if a lat/lng is not found
Browse files Browse the repository at this point in the history
Stop the search if the first 5 timezone objects found by the index
do not contain the input lat/lng thus saving computing resources
  • Loading branch information
noandrea committed Jun 25, 2024
1 parent a194645 commit 37cff76
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
11 changes: 11 additions & 0 deletions db/rtree.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
7 changes: 0 additions & 7 deletions web/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 37cff76

Please sign in to comment.