Last active
October 18, 2021 08:11
-
-
Save toastal/993b1725b8a7c94c9c01 to your computer and use it in GitHub Desktop.
Recursive Mulitsort
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
let data = | |
[ [{value: 0}, {value: 3}, {value: "c"}] | |
, [{value: 2}, {value: 1}, {value: "a"}] | |
, [{value: 1}, {value: 2}, {value: "b"}] | |
, [{value: 1}, {value: 3}, {value: "b"}] | |
]; | |
let sorter = [[1, false], [2, false]]; | |
// getVals : [[{value: a}]] -> [[a]] | |
const getVals = (data) => data.map((row) => row.map((item) => item.value)); | |
// rowValueSorter : [[Int, Bool]] -> ([a, b] -> Int) | |
const rowValueSorter = (sorter) => { | |
//var canLocaleCompare = "localeCompare" in String.prototype; | |
return function compare(a, b) { | |
return (function recurSorter(head, tail) { | |
var idx = head[0], asc = head[1]; | |
var aval = a[idx].value, bval = b[idx].value; | |
//var shouldLocaleCompare = | |
// canLocaleCompare && typeof aval === "string" && typeof bval === "string"; | |
var aLTb = aval < bval, aGTb = aval > bval; | |
if ((asc && aGTb) || (!asc && aLTb)) { | |
return 1; | |
} else if ((asc && aLTb) || (!asc && aGTb)) { | |
return -1; | |
} else { | |
if (tail.length === 0) { | |
return 0; | |
} else { | |
return recurSorter(tail.shift(), tail); | |
} | |
} | |
}(sorter[0], sorter.slice(1))); | |
} | |
} | |
console.clear(); | |
console.log("unsorted"); | |
console.table(getVals(data)); | |
data.sort(rowValueSorter(sorter)); | |
console.log("sorted"); | |
console.table(getVals(data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment