Add stableSort function
This commit is contained in:
8
test/stableSort/stableSort.js
Normal file
8
test/stableSort/stableSort.js
Normal file
@ -0,0 +1,8 @@
|
||||
var stableSort = (arr, compare) =>
|
||||
arr
|
||||
.map((item, index) => ({ item, index }))
|
||||
.sort((a, b) =>
|
||||
((result = compare(a.item, b.item)) => (result !== 0 ? result : a.index - b.index))()
|
||||
)
|
||||
.map(({ item }) => item);
|
||||
module.exports = stableSort;
|
||||
25
test/stableSort/stableSort.test.js
Normal file
25
test/stableSort/stableSort.test.js
Normal file
@ -0,0 +1,25 @@
|
||||
const test = require('tape');
|
||||
const stableSort = require('./stableSort.js');
|
||||
|
||||
test('Testing stableSort', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof stableSort === 'function', 'stableSort is a Function');
|
||||
//t.deepEqual(stableSort(args..), 'Expected');
|
||||
//t.equal(stableSort(args..), 'Expected');
|
||||
//t.false(stableSort(args..), 'Expected');
|
||||
//t.throws(stableSort(args..), 'Expected');
|
||||
|
||||
// test if js engine's Array#sort implementation is stable
|
||||
// https://gist.github.com/leeoniya/5816476
|
||||
var str = 'abcdefghijklmnopqrstuvwxyz';
|
||||
var compare = (a, b) => ~~(str.indexOf(b) / 2.3) - ~~(str.indexOf(a) / 2.3);
|
||||
|
||||
var input = str.split('');
|
||||
var output = stableSort(input, compare);
|
||||
|
||||
t.equal(output.join(''), 'xyzvwtursopqmnklhijfgdeabc');
|
||||
t.notDeepEqual(input, output);
|
||||
|
||||
t.end();
|
||||
});
|
||||
Reference in New Issue
Block a user