From: Jean Privat Date: Mon, 30 Mar 2015 12:25:05 +0000 (+0700) Subject: lib/sorter: add `MapRead::values_sorted_by_key` X-Git-Tag: v0.7.3~3^2~7 X-Git-Url: http://nitlanguage.org lib/sorter: add `MapRead::values_sorted_by_key` Signed-off-by: Jean Privat --- diff --git a/lib/standard/collection/sorter.nit b/lib/standard/collection/sorter.nit index cfcc376..190f30a 100644 --- a/lib/standard/collection/sorter.nit +++ b/lib/standard/collection/sorter.nit @@ -250,6 +250,25 @@ interface Comparator end +redef class MapRead[K,V] + # Return an array of all values sorted with their keys using `comparator`. + # + # ~~~ + # var map = new HashMap[Int, String] + # map[10] = "ten" + # map[2] = "two" + # map[1] = "one" + # assert map.values_sorted_by_key(default_comparator) == ["one", "two", "ten"] + # assert map.values_sorted_by_key(alpha_comparator) == ["one", "ten", "two"] + # ~~~ + fun values_sorted_by_key(comparator: Comparator): Array[V] + do + var keys = self.keys.to_a + comparator.sort(keys) + return [for k in keys do self[k]] + end +end + # This comparator uses the operator `<=>` to compare objects. # see `default_comparator` for an easy-to-use general stateless default comparator. class DefaultComparator