Implementing a Bag in LotusScript

A Bag is a collection that keeps track of the number of times each element occurs in the collection. The name was inspired by the Bag implementation from the Apache Jakarta Commons Collections.

Please note that this is a quick implementation and it only handles simple datatypes – no support for objects at present.

The code is of cause documented using LotusScript.doc… 🙂

'/**
' * Implementation of a bag that is a collection that keeps track of the
' * number of times an element occurs in a collection.
' */
Public Class Bag
   'declarations
   Private pElements As Vector
   Private pElementCount List As Integer

   '/**
   ' * Constructor.
   ' */
   Public Sub New()
      Set Me.pElements = New Vector()
   End Sub

   '/**
   ' * Adds an element to the bag.
   ' * @param e The element to add.
   ' */
   Public Sub AddElement(e As Variant)
      'declarations
      Dim hash_e As Variant

      'add the element to the vector
      Call Me.pElements.AddElement(e)

      'do we have a count for this already
      If Not Iselement(Me.pElementCount(e)) Then
         'we do not have a count
         Me.pElementCount(e) = 1
      Else
         Me.pElementCount(e) = Me.pElementCount(e) + 1
      End If
   End Sub

   '/**
   ' * Get a count of the number of times an element occurs in the bag.
   ' *
   ' * @param e The element for look for.
   ' * @return Count of the times the element occurs (0 if it doesn't occur)
   ' */
   Public Function GetCount(e As Variant) As Long
      'declarations
      Dim hash_e As Variant
      If Not Iselement(Me.pElementCount(e)) Then
         GetCount = 0
      Else
         GetCount = Me.pElementCount(e)
      End If
   End Function

   '/**
   ' * Returns an array of the unique elements added.
   ' *
   ' * @return Array of unique elements added.
   ' */
   Public Function GetUnique() As Variant
      Dim v() As Variant
      Dim i As Integer
      Forall k In Me.pElementCount
         Redim Preserve v(i)
         v(i) = Listtag(k)
         i = i + 1
      End Forall
      GetUnique = v
   End Function

End Class

3 thoughts on “Implementing a Bag in LotusScript”

  1. Chad,

    I use the excellent collection LotusScript classes by Johan Känngaard. Johan has written a Vector, Hashtable, Stack and Queue. All collections (where it makes sense) can be enumerated using an Enumeration interface. The classes has recently been LGPL’ed which is really nice.

    The Bag is built using the Vector as you noted. If you see in the source for LotusScript.doc (the “CLASS: Collections” script library) I also use the classes heavily there.

    Link to Johans website

    Direct link to the Vector class

Comments are closed.