on master help sign in
Add sortBy function.
beeaa38Max Goldstein
libraries/List.elm+5−1
@@ -22,7 +22,7 @@ list must have the same type.
22@docs sum, product, maximum, minimum, all, any, and, or
22@docs sum, product, maximum, minimum, all, any, and, or
23
23
24# Sorting
24# Sorting
25−@docs sort
25+@docs sort, sortBy
26-}
26-}
27
27
28import open Basics
28import open Basics
@@ -231,3 +231,7 @@ repeat = Native.List.repeat
231{-| Sort a list in ascending order. -}
231{-| Sort a list in ascending order. -}
232sort : [comparable] -> [comparable]
232sort : [comparable] -> [comparable]
233sort = Native.List.sort
233sort = Native.List.sort
234+
235+{-| Sort a list by a given comparison function. -}
236+sortBy : (a -> comparable) -> [a] -> [a]
237+sortBy = Native.List.sortBy
libraries/Native/List.js+9
@@ -220,6 +220,14 @@ Elm.Native.List.make = function(elm) {
220 return fromArray(toArray(xs).sort(cmp));
220 return fromArray(toArray(xs).sort(cmp));
221 }
221 }
222
222
223+ function sortBy(f, xs) {
224+ function cmp(a,b) {
225+ var ord = Utils.compare(f(a))(f(b)).ctor;
226+ return ord === 'EQ' ? 0 : ord === 'LT' ? -1 : 1;
227+ }
228+ return fromArray(toArray(xs).sort(cmp));
229+ }
230+
223 function nth(xs, n) {
231 function nth(xs, n) {
224 return toArray(xs)[n];
232 return toArray(xs)[n];
225 }
233 }
@@ -298,6 +306,7 @@ Elm.Native.List.make = function(elm) {
298 zipWith:F3(zipWith),
306 zipWith:F3(zipWith),
299 zip:F2(zip),
307 zip:F2(zip),
300 sort:sort,
308 sort:sort,
309+ sortBy:F2(sortBy),
301 nth:F2(nth),
310 nth:F2(nth),
302 take:F2(take),
311 take:F2(take),
303 drop:F2(drop),
312 drop:F2(drop),