VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "CDS_CompoundIntervals"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
' === Упорядоченный набор непересекающихся интервалов  ====
' Shared module version: 20210511
' Tested in: TestCommons
' Depends on: CDS_Interval
' Required reference:
Option Explicit

Public items_ As Collection ' of CDS_Interval

Private Sub Class_Initialize()
  Call Clear
End Sub

Public Property Get Count() As Long
  Count = items_.Count
End Property

Public Property Get IsEmpty() As Boolean
  IsEmpty = Count = 0
End Property

Public Function AddItem(nStart&, nFinish&)
  If nFinish < nStart Then _
    Exit Function
  Call AddInternal(CreateInterval(nStart, nFinish))
End Function

Public Function Clear()
  Set items_ = New Collection
End Function

' =======
Private Function AddInternal(ByRef newItem As CDS_Interval)
  Dim nItem&: nItem = 1
  Dim nextItem As CDS_Interval
  For Each nextItem In items_
    If nextItem.start_ > newItem.finish_ Then
      Call items_.Add(newItem, Before:=nItem)
      Exit Function
    ElseIf nextItem.finish_ >= newItem.finish_ Then
      If nextItem.start_ > newItem.start_ Then _
        nextItem.start_ = newItem.start_
      Exit Function
    ElseIf nextItem.finish_ >= newItem.start_ Then
      newItem.start_ = nextItem.start_
      Call items_.Remove(nItem)
      Call AddInternal(newItem)
      Exit Function
    End If
    nItem = nItem + 1
  Next nextItem
  Call items_.Add(newItem)
End Function

Private Function CreateInterval(nStart&, nFinish&) As CDS_Interval
  Dim iNewItem As New CDS_Interval: Call iNewItem.Init(nStart, nFinish)
  Set CreateInterval = iNewItem
End Function
