Skip to content

Instantly share code, notes, and snippets.

@callionica
Last active February 9, 2016 19:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callionica/289d33bc6ec1629ffd36 to your computer and use it in GitHub Desktop.
Save callionica/289d33bc6ec1629ffd36 to your computer and use it in GitHub Desktop.
// Types work but are not optimal - no error handling
// Demo in response to https://gist.github.com/sketchytech/029c00a74a4217a89797
extension CollectionType {
func reorder<T>(sorter: [(index: Self.Index, element: T)]) -> Array<Self.Generator.Element> {
return sorter.map({self[$0.index]})
}
}
func sortColumns<T0, T1>(_ col0: Array<T0>, _ col1: Array<T1>, _ cmp: (T0,T0)->Bool) -> (Array<T0>, Array<T1>) {
let sorter = col0.enumerate().sort({ cmp($0.element, $1.element) })
return (col0.reorder(sorter), col1.reorder(sorter))
}
func sortColumns<T0, T1, T2>(_ col0: Array<T0>, _ col1: Array<T1>, _ col2: Array<T2>, _ cmp: (T0,T0)->Bool) -> (Array<T0>, Array<T1>, Array<T2>) {
let sorter = col0.enumerate().sort({ cmp($0.element, $1.element) })
return (col0.reorder(sorter), col1.reorder(sorter), col2.reorder(sorter))
}
// Add as many overloads as you need
let col0 = [ 4 , 3 , 1 , 5 ]
let col1 = [ "x", "z" , "y" , "w"]
let col2 = [ "c", "b" , "a" , "c"]
let col3 = [10.4, 16.8 , 7.2 , 1.4 ]
// Sort by col0 ascending
let result1 = sortColumns(col0, col1, <);
print(result1)
// Sort by col1 descending
let result2 = sortColumns(col1, col0, col2, >);
print(result2)
@callionica
Copy link
Author

SketchyTech asked a question about how to sort a data table where columns are stored in separate arrays.

https://gist.github.com/sketchytech/029c00a74a4217a89797

This gist is a quick demo of how to do it simply and while preserving type information.

The key element of the solution is to call enumerate().sort() on the column used to define the sort order and then call map() on the result to pick elements from each of the sorted columns using the appropriate index.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment