Sorting array with different order
Grzeogorz Łuszczek" <grzegorz at piklus.pl>
Grzeogorz Łuszczek" <grzegorz at piklus.pl>
Wed Aug 7 06:51:13 PDT 2013
I'm writing small web server to serve data as JSON. This data
could be sorted based on various parameters (order and field to
sort).
In this example I will use only 2 classes (but I need serve 10-20
classes and each class have 5-10 attributes):
class Port {
int number;
Host[] host;
}
class Host {
string macAddress;
string ipAddress;
}
I have idea to use this struct:
struct Sort {
string order = "desc"; // Sort order - DESC/ASC
string sort_by; // Filed to sort by
}
To create an associative array with sort function:
static this(){
portSortMethods[ Sort( "desc", "number" ) ] = &sort!( "a.number
> b.number", SwapStrategy.unstable, Port[] );
portSortMethods[ Sort( "asc", "number" ) ] = &sort!( "a.number
< b.number", SwapStrategy.unstable, Port[] );
hostSortMethods[ Sort( "desc", "macAddress" ) ] = &sort!(
"a.macAddress > b.macAddress", SwapStrategy.unstable, Host[] );
hostSortMethods[ Sort( "asc", "macAddress" ) ] = &sort!(
"a.macAddress < b.macAddress", SwapStrategy.unstable, Host[] );
hostSortMethods[ Sort( "desc", "ipAddress" ) ] = &sort!(
"a.ipAddress > b.ipAddress", SwapStrategy.unstable, Host[] );
hostSortMethods[ Sort( "asc", "ipAddress" ) ] = &sort!(
"a.ipAddress < b.ipAddress", SwapStrategy.unstable, Host[] );
}
And write function like this for Hosts:
Hosts[] sortHosts( Host[] collection, string order, string by ) {
auto sortMethod = hostsSortMethods[ Sort( "desc", "macAddress )
];
return sortMethod( collection ).release();
}
But I have problem with type of portSortMethod and hostSortMethod.
I will be glad if someone could help me with my problem.
More information about the Digitalmars-d
mailing list