diff --git a/Project.toml b/Project.toml index c58ebba..4c796c4 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "TimeSpans" uuid = "bb34ddd2-327f-4c4a-bfb0-c98fc494ece1" authors = ["Beacon Biosignals, Inc."] -version = "1.1.0" +version = "1.2.0" [deps] ArrowTypes = "31f734f8-188a-4ce0-8406-c8a06bd891cd" diff --git a/src/TimeSpans.jl b/src/TimeSpans.jl index 4e62856..dcf4b90 100644 --- a/src/TimeSpans.jl +++ b/src/TimeSpans.jl @@ -399,6 +399,18 @@ function invert_spans(spans, parent_span) return gaps end +""" + intersect(span_1, span_2) + +Returns a timespan that consists of the intersection of two timespans. + +Throws an `ArgumentError` if there is not overlap between the spans. +""" +function intersect(a, b) + overlaps(a, b) || throw(ArgumentError("provided spans must overlap")) + return TimeSpan(max(start(a), start(b)), min(stop(a), stop(b))) +end + ##### ##### Package extensions (TODO: remove this section once we require Julia 1.9+) ##### diff --git a/test/runtests.jl b/test/runtests.jl index 9140e13..cf41267 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -264,6 +264,18 @@ end @test test_vec == [] end +@testset "intersect" begin + test_span_1 = TimeSpan(10, 100) + test_span_2 = TimeSpan(20, 80) + test_span_3 = TimeSpan(80, 120) + non_intersecting_span = TimeSpan(101, 150) + + @test TimeSpans.intersect(test_span_1, test_span_2) == test_span_2 + @test TimeSpans.intersect(test_span_1, test_span_3) == TimeSpan(80, 100) + + @test_throws ArgumentError TimeSpans.intersect(test_span_1, non_intersecting_span) +end + @testset "extensions" begin @testset "ArrowTypes" begin using ArrowTypes