test.js
1 import * as assert from 'assert'; 2 import * as fc from 'fast-check'; 3 import { stableSort } from './implem'; 4 5 const count = (tab, element) => tab.filter(v => v === element).length; 6 7 describe('stable sort', () => { 8 it('should contain the same items', () => 9 fc.assert( 10 fc.property(fc.array(fc.integer()), data => { 11 const sorted = stableSort(data.slice(0), (a, b) => a - b); 12 assert.equal(sorted.length, data.length); 13 for (const item of data) assert.equal(count(sorted, item), count(data, item)); 14 }) 15 )); 16 it('should produce ordered array', () => 17 fc.assert( 18 fc.property(fc.array(fc.integer()), data => { 19 const sorted = stableSort(data, (a, b) => a - b); 20 for (let idx = 1; idx < sorted.length; ++idx) assert.ok(sorted[idx - 1] <= sorted[idx]); 21 }) 22 )); 23 it('should be stable', () => 24 fc.assert( 25 fc.property(fc.array(fc.record({ key1: fc.nat(5), key2: fc.nat(5) })), data => { 26 const singleSort = stableSort(data, (a, b) => { 27 if (a.key2 < b.key2) return -1; 28 else if (a.key2 > b.key2) return 1; 29 return a.key1 - b.key1; 30 }); 31 const sorted = stableSort(stableSort(data, (a, b) => a.key1 - b.key1), (a, b) => a.key2 - b.key2); 32 assert.deepStrictEqual(sorted, singleSort); 33 }) 34 )); 35 });