Last active
February 7, 2018 20:27
-
-
Save simov/aa3b9e534039fa00ac3c1b4905605069 to your computer and use it in GitHub Desktop.
Test Stable Sort
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
// https://github.com/mziccard/node-timsort/#stability | |
var t = require('assert') | |
// sorted by weight | |
var input = [ | |
{ height: 100, weight: 80 }, | |
{ height: 90, weight: 90 }, | |
{ height: 70, weight: 95 }, | |
{ height: 100, weight: 100 }, | |
{ height: 80, weight: 110 }, | |
{ height: 110, weight: 115 }, | |
{ height: 100, weight: 120 }, | |
{ height: 70, weight: 125 }, | |
{ height: 70, weight: 130 }, | |
{ height: 100, weight: 135 }, | |
{ height: 75, weight: 140 }, | |
{ height: 70, weight: 140 } | |
] | |
// sorted by height (using stableSort) | |
var target = [ | |
{ height: 70, weight: 95 }, | |
{ height: 70, weight: 125 }, | |
{ height: 70, weight: 130 }, | |
{ height: 70, weight: 140 }, | |
{ height: 75, weight: 140 }, | |
{ height: 80, weight: 110 }, | |
{ height: 90, weight: 90 }, | |
{ height: 100, weight: 80 }, | |
{ height: 100, weight: 100 }, | |
{ height: 100, weight: 120 }, | |
{ height: 100, weight: 135 }, | |
{ height: 110, weight: 115 } | |
] | |
var stableSort = (arr, compare) => arr | |
.map((item, index) => ({item, index})) | |
.sort((a, b) => compare(a.item, b.item) || a.index - b.index) | |
.map(({item}) => item) | |
var compare = (a, b) => a.height - b.height | |
// passes | |
t.deepStrictEqual(stableSort(input, compare), target) | |
// throws | |
t.deepStrictEqual(input.sort(compare), target) | |
// Array.sort() expects something like this | |
var unstable = [ | |
{ height: 70, weight: 140 }, | |
{ height: 70, weight: 95 }, | |
{ height: 70, weight: 125 }, | |
{ height: 70, weight: 130 }, | |
{ height: 75, weight: 140 }, | |
{ height: 80, weight: 110 }, | |
{ height: 90, weight: 90 }, | |
{ height: 100, weight: 100 }, | |
{ height: 100, weight: 80 }, | |
{ height: 100, weight: 135 }, | |
{ height: 100, weight: 120 }, | |
{ height: 110, weight: 115 } | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment