- Joined
- Jun 24, 2017
- Messages
- 184
I have found this handy over the years. Just import sortitem and use it as in the test function. Could be a boon in particular for those who don't feel comfortable extending lists etc. themselves.
Code:
Strict
' Helper class for sorting items of any kind (objects or primitive types) without making a new class, compare methods etc.
' You just need to be able to calculate a float value for each item
Function Test_SortItem:Void()
Local items:String[] = [ "banana", "apple", "pear", "melon", "avocado", "grapefruit", "plum" ]
Local sorter:SortItem< String > = New SortItem< String >()
For Local item:String = Eachin items
sorter.Add( item, item.Length() )
Next
Local sortedList:List< String > = sorter.Sort()
For Local item:String = Eachin sortedList
Print item
Next
End
Class SortItem< T >
Field data:SIList< T >
Method New()
data = New SIList< T >()
End
Method Clear:Void()
data.Clear()
End
Method Add:Void( item:T, value:Float )
data.AddLast( New SIDatum< T >( item, value ) )
End
Method Sort:List< T >( ascending:Int = True )
data.Sort( ascending )
Local res:List< T > = New List< T >()
For Local sid:SIDatum< T > = Eachin data
res.AddLast( sid.item )
Next
Return res
End
End
Private
Class SIDatum< T >
Field item:T
Field value:Float
Method New( item:T, value:Float )
Self.item = item
Self.value = value
End
End
Class SIList< T > Extends List< SIDatum< T > >
Method New( data:SIDatum< T >[] )
Super.New( data )
End
Method Equals:Bool( lhs:SIDatum< T >, rhs:SIDatum< T > )
Return lhs.value = rhs.value
End
Method Compare:Int( lhs:SIDatum< T >, rhs:SIDatum< T > )
If lhs.value < rhs.value
Return -1
End
Return lhs.value > rhs.value
End
End
Last edited: