Created
June 29, 2016 08:27
-
-
Save namlook/bc77a1cf7f8d0d044a5fe30bad25e1cb to your computer and use it in GitHub Desktop.
Dynamically sort by field in Elm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Dict | |
import List | |
import Html exposing (text) | |
type alias Expense = | |
{ title : String | |
, amount: Float | |
} | |
expenses = [{title = "bbb", amount = 3}, {title = "aaa", amount = 5}] | |
compareBy accessor a b = compare (accessor a) (accessor b) | |
expensesAccessors = | |
Dict.fromList [ ( "title", compareBy .title ), ( "amount", compareBy .amount ) ] | |
sortByField : String -> Dict.Dict String (a -> a -> Order) -> List a -> List a | |
sortByField fieldname accessors list = | |
case Dict.get fieldname accessors of | |
Just fn -> | |
List.sortWith fn list | |
Nothing -> | |
list | |
sortedExpenses = sortByField "title" expensesAccessors expenses | |
main = | |
text <| toString sortedExpenses |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment