Skip to content

Commit

Permalink
fix: sort through-routed trips numerically (#2257)
Browse files Browse the repository at this point in the history
  • Loading branch information
lemald authored Oct 12, 2023
1 parent c095d76 commit 5b61262
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
21 changes: 16 additions & 5 deletions lib/schedule/hastus/trip.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ defmodule Schedule.Hastus.Trip do
alias Schedule.{Block, Route, Trip}
alias Schedule.Hastus.{Place, Run, Schedule}

@through_routed_suffix_regex ~r/_(\d+)$/

@type t :: %__MODULE__{
schedule_id: Schedule.id(),
run_id: Run.id(),
Expand Down Expand Up @@ -98,19 +100,28 @@ defmodule Schedule.Hastus.Trip do

@spec expand_through_routed_trips([t()], MapSet.t()) :: [t()]
def expand_through_routed_trips(trips, gtfs_trip_ids) do
through_routed_suffix_regex = ~r/_\d+$/

original_id_to_through_routed_trip_ids =
gtfs_trip_ids
|> Enum.filter(&Regex.match?(through_routed_suffix_regex, &1))
|> Enum.group_by(&String.replace(&1, through_routed_suffix_regex, ""))
|> Enum.filter(&Regex.match?(@through_routed_suffix_regex, &1))
|> Enum.group_by(&String.replace(&1, @through_routed_suffix_regex, ""))

trips
|> Enum.flat_map(fn trip ->
through_routed_trip_ids = Map.get(original_id_to_through_routed_trip_ids, trip.trip_id)

if through_routed_trip_ids do
Enum.map(through_routed_trip_ids, &%__MODULE__{trip | trip_id: &1})
through_routed_trip_ids
|> Enum.sort_by(fn trip_id ->
try do
[[suffix]] =
Regex.scan(@through_routed_suffix_regex, trip_id, capture: :all_but_first)

String.to_integer(suffix)
rescue
_ -> 0
end
end)
|> Enum.map(&%__MODULE__{trip | trip_id: &1})
else
[trip]
end
Expand Down
2 changes: 1 addition & 1 deletion test/schedule/hastus/trip_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ defmodule Schedule.Hastus.TripTest do
test "replaces a single consolidated through_routed trip with multiple differentiated trips" do
hastus_trip1 = build(:hastus_trip, trip_id: "nonthrough_routed")
hastus_trip2 = build(:hastus_trip, trip_id: "through_routed")
gtfs_trip_ids = ["nonthrough_routed", "through_routed_1", "through_routed_2"]
gtfs_trip_ids = ["nonthrough_routed", "through_routed_2", "through_routed_1"]

result =
[hastus_trip1, hastus_trip2]
Expand Down

0 comments on commit 5b61262

Please sign in to comment.