Re: can i make this better?

new topic     » goto parent     » topic index » view thread      » older message » newer message

Greg wrote:

> I want to sort the results from dir() so that all the directories are first,
> then the files, in alphabetical order. I'm using custom_sort() and
> compare(), so far this is what I have:
>
> function compare_dir(object x1, object x2)
> integer ret
>
>     if find('d', x1[D_ATTRIBUTES]) then
>         if find('d', x2[D_ATTRIBUTES]) then
>             ret = compare(lower(x1[D_NAME]), lower(x2[D_NAME]))
>         else
>             ret = -1
>         end if
>     else
>         if find('d', x2[D_ATTRIBUTES]) then
>             ret = 1
>         else
>             ret = compare(lower(x1[D_NAME]), lower(x2[D_NAME]))
>         end if
>     end if
>
>     return ret
> end function


I believe I would code it like this (not tested), this way we only
have to deal with 3 cases:

function compare_dir (object x1, object x2)
   integer type1, type2

   type1 = find('d', x1[D_ATTRIBUTES])    -- 0 => file, != 0 => dir
   type2 = find('d', x2[D_ATTRIBUTES])

   if type1 = type2 then
      return compare(lower(x1[D_NAME]), lower(x2[D_NAME]))
   elsif type1 != 0 then
      return -1
   else
      return 1
   end if
end function


> function sort_dir(sequence x)
>     return custom_sort(routine_id("compare_dir"), x)
> end function
>
>
> Right now this works, but I feel all those if statements could be more
> efficient, it just looks messy to me. Can anyone patch this up?
>
> ~Greg

Regards,
   Juergen

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu