smalltalktimespan

Is there a function to check intersection of two timespans in smalltalk?


Is there a built-in function in smalltalk that takes as input two timespans, and checks whether they intersect?

As an example: the two timespans 2018/01/01-2018/01/05 and 2018/01/03-2018/01/10 do intersect and this function should output true.

Update: I implemented the following method:

checkIntersection: aTimespan
"returns true if two timespans overlap and false if not"
| start1 end1 start2 end2 |
start1 := self start.
end1 := self end.
start2 := aTimespan start.
end2 := aTimespan end.
(start1 = start2)
    ifTrue: [ ^true ].
(start1 = end2)
    ifTrue: [ ^true ].
(end1 = start2)
    ifTrue: [ ^true ].
(end1 = end2)
    ifTrue: [ ^true ].
(start2 < start1 and: [ (start1 < end2) ])
    ifTrue: [ ^true ].
(start2 < end1 and: [ (end1 < end2) ])
    ifTrue: [ ^true ].  
^false

It works, but it is quite messy, especially the if and: statements.


Solution

  • In Squeak there is the following method

    Timespan >> #intersection: aTimespan
    
         "Return the Timespan both have in common, or nil"
    
         | aBegin anEnd |
         aBegin := self start max: aTimespan start.
         anEnd := self end min: aTimespan end.
         anEnd < aBegin ifTrue: [^nil].
    
         ^ self class starting: aBegin ending: anEnd
    

    So, you could compute the intersection and then check for nil or adapt this code to get what you want.

    As a side note, I would suggest using the selector #intersects: rather than #checkIntersection: