For sorted arrays of structs a modified version of StefanKarpinski solution would look like the example below:
struct TimeEvent
date::Dates.DateTime
type::String
end
v = [
TimeEvent(DateTime("2019-03-01"),"data_release")
TimeEvent(DateTime("2019-02-01"),"data_release")
TimeEvent(DateTime("2019-05-01"),"data_release")
]
new_event=TimeEvent(DateTime("2019-04-01"),"data_release")
# Sort Events
sort!(v, by = v -> v.date, rev=true)
# Define Function
sortedStructInsert!(v::Vector, x) = (splice!(v,
searchsorted(v,x,by= v->v.date, rev=true), [x]); v)
# Call function
sortedStructInsert!(v, new_event)
4-element Vector{TimeEvent}:
TimeEvent(DateTime("2019-05-01T00:00:00"), "data_release")
TimeEvent(DateTime("2019-04-01T00:00:00"), "data_release")
TimeEvent(DateTime("2019-03-01T00:00:00"), "data_release")
TimeEvent(DateTime("2019-02-01T00:00:00"), "data_release")
The example below allows you to specify which field of the struct is the one that sorts, for a more generic implementation.
sortedStructInsert!(v::Vector, x,symbol) = (splice!(v,
searchsorted(v,x,by= v->getproperty(v,symbol), rev=true), [x]); v)
sortedStructInsert!(v, new_event, :date)
insert_and_dedup!(v::Vector, x) = (splice!(v, searchsorted(v,x), x); v)
instead. – Marinetti