Hi Alexandre,
IMO the isKindOf:, apart from being ugly, will hurt performance badly.
Why not apply aSortBlockOrSymbol to the first element and then choose the
block appropriately? e.g.
aSortBlockOrSymbol isSymbol
ifTrue:
[(#(true false) includes: (self first perform:
aSortBlockOrSymbol)
ifTrue:
[[:a :b | (a perform: aSortBlockOrSymbol)]]
ifFalse:
[[:a :b | (a perform: aSortBlockOrSymbol) < (b
perform: aSortBlockOrSymbol)]]]
...
Nicer to read and faster, no?
On Tue, Mar 11, 2014 at 8:17 AM, Alexandre Bergel
<[email protected]>wrote:
> hi Uko,
>
> For Roassal, we have a #sortedAs: defined on all collections
>
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
> SequenceableCollection>>sortedAs: aSortBlockOrSymbol
> "Answer a SortedCollection whose elements are the elements of the
> receiver. The sort order is defined by the argument, aSortBlock."
> "Return a new collection. This method does not do a side effect"
>
> | aSortedCollection aSortBlock |
> aSortedCollection := SortedCollection new: self size.
> aSortBlock :=
> aSortBlockOrSymbol isSymbol
> ifTrue: [ [:a :b | |t1 t2|
> t1 := (a perform:
> aSortBlockOrSymbol).
> t2 := (b perform:
> aSortBlockOrSymbol).
> ((t1 isKindOf:
> Boolean) and: [t2 isKindOf: Boolean])
> ifTrue: [
> t1 ]
> ifFalse: [
> t1 < t2 ] ] ]
> ifFalse: [
> (aSortBlockOrSymbol numArgs = 1)
> ifTrue: [ [ :v1 :v2 |
> (aSortBlockOrSymbol value: v1) < (aSortBlockOrSymbol value: v2) ] ]
> ifFalse: [ aSortBlockOrSymbol ] ].
> aSortedCollection sortBlock: aSortBlock.
> aSortedCollection addAll: self.
> ^ aSortedCollection
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
>
> You can use it for example:
> (1 to: 4) sortedAs: #odd
> => a SortedCollection(1 3 2 4)
>
> Collection withAllSubclasses sortedAs: #numberOfMethods
> => a SortedCollection(HashBag IdentityHashBag ...)
>
> This is really handy. It should be part of Pharo I believe.
>
> Cheers,
> Alexandre
>
>
> On Mar 11, 2014, at 5:19 AM, Yuriy Tymchuk <[email protected]> wrote:
>
> > Hi guys.
> >
> > This is a thing that I encounter quite often.
> >
> > Eg I have a collection of projects and I want to sort them by creation
> date. It would be nice to be able to do something like:
> >
> > projects sortByProp: #creationDate
> >
> > or by birth date of the author
> >
> > projects sortByProp: [ :proj | proj author birthDate ]
> >
> > Maybe I'm wrong, but as I've told already I encounter it quite often and
> writing something like
> >
> > projects sortBy: [ :prev :next | prev creationDate <= next creationDate ]
> >
> > is boring for me.
> >
> > Cheers.
> > Uko
>
> --
> _,.;:~^~:;._,.;:~^~:;._,.;:~^~:;._,.;:~^~:;._,.;:
> Alexandre Bergel http://www.bergel.eu
> ^~:;._,.;:~^~:;._,.;:~^~:;._,.;:~^~:;._,.;:~^~:;.
>
>
>
>
>
--
best,
Eliot