On 09/08/2023 00:15, Bob Sneidar via use-livecode wrote:
Has anyone come across a need to sort a numbered array by the values of the
different keys? Here you go.
Absolutely I have needed that quite often now. I tend to use sequences
(numbered arrays) often - maybe too often.
Up until now I've just done the sorting in the "traditional" way (i.e.
using multiple "sort" commands), like
put seqAsLines(sQ2) into tKeys
sort lines of tKeys numeric by sQ2[each]["anumber"]
sort lines of tKeys by sQ2[each]["thecategory"]
rebuildSeq sQ2, tKeys
(the functions seqAsLines and rebuildSeq are included in the code
snippet below).
But I really like your idea of having a handler that can be given
multiple sort keys, and just does it all, so I took a detailed look.
First - a couple of little bugs for you.
Keep in mind that there is no error checking so I have no idea what would
happen if you provided a sort key that didn’t exist in the array.
on sortNumberedArray @pArrayDataA, pSortKeys
switch
case tKeyWord is among the items of "asc,ascending,desc,descending"
put tKeyWord into tSortKeysA [i] ["sortorder"]
break
case tKeyWord is "International,Numeric,datetime,text,binary"
'is' should be 'is among the items of'
put tKeyWord into tSortKeysA [i] ["sorttype"]
break
default
put word 1 to x of tSortIndex into tSortKeysA [i] ["sortvalue"]
end switch
end repeat
end repeat
Secondly, not sure if it's a bug or simply a limitation - the code fails
if one of the array keys to use for sorting is one of
"asc,desc,numeric,...".
And - overall, an alternate suggestion. I think your way is a bot complex.
Combining my "traditional" way as above, and your example, I came up
with a simpler way to do the same thing:
on simpleSortNumberedArray @pArrayDataA, pSortKeys
local tKeys, tSeq, tOneSortKey, tSortCommand
put seqAsLines(pArrayDataA) into tKeys
repeat with I = the number of items in pSortKeys down to 1
put item I of pSortKeys into tOneSortKey
put "sort lines of tKeys" && word 2 to -1 of tOneSortKey && \
"by pArrayData[each][" && word 1 of tOneSortKey && "]"
into tSortCommand
do tSortCommand
end repeat
rebuildSeq pArrayDataA, tKeys
end simpleSortNumberedArray
function seqAsLines pSeq
local tRes
repeat with i = 1 to the number of elements in pSeq
put i & CR after tRes
end repeat
return tRes
end seqAsLines
command rebuildSeq @pSeq, pList
local tResQ, tCount
repeat for each line L in pList
add 1 to tCount
put pSeq[L] into tResQ[tCount]
end repeat
put tResQ into pSeq
end rebuildSeq
This is simpler and, I think, easier to understand. And it's certainly
much faster: takes 89 msec for my test case rather than 3416 msecs.
Alex.
_______________________________________________
use-livecode mailing list
use-livecode@lists.runrev.com
Please visit this url to subscribe, unsubscribe and manage your subscription
preferences:
http://lists.runrev.com/mailman/listinfo/use-livecode