UNPKG

open-data

Version:

A package filled with data structures, sort algorithms, selections, and more to come

93 lines 3.48 kB
const sorts = require('../sorts.js'); const assert = require('assert'); const ranArray = (len=100, range=100) => { let i =[]; for (i; i.length < len; i.push(~~(Math.random()*range))); return i; } describe('Sorts', () => { describe('All sorts', () => { let testArrs = []; beforeEach(() => { testArrs = []; }); it('Should sort numbers', () => { for (let i = 0; i < 20; i ++) { testArrs.push(ranArray(~~(Math.random() * 32), ~~(Math.random() * 3000))); } for (let sort in sorts) { let s = sorts[sort]; if (s !== sorts.isSorted) { for (let test of testArrs) { if (s(test).toString() !== test.sort((a,b) => a-b).toString()) { throw new Error(`${sort} failed at sorting numbers, Expected: ${test.sort((a,b) => a-b).toString()} Actual: ${s(test).toString()}`) } } console.log(`${sort} w/ numbers O K`); } }; }); it('should sort strings', () => { for (let i = 0; i < 20; i ++) { testArrs.push(ranArray(~~(Math.random() * 32), ~~(Math.random() * 3000)).map(e => e.toString(32))); } for (let sort in sorts) { let s = sorts[sort]; if (s !== sorts.isSorted && s !== sorts.radix) { for (let test of testArrs) { if (s(test).toString() !== test.sort().toString()) { throw new Error(`${sort} failed at sorting strings in ${test}, Expected: ${test.sort().toString()} Actual: ${s(test).toString()}`); } } console.log(`${sort} w/ strings O K`); } else if (s === sorts.radix) { console.log('Radix does not yet support lexographic sort'); } } }); it('should sort booleans', () => { for (let i = 0; i < 20; i ++) { testArrs.push(ranArray(~~(Math.random() * 32), ~~(Math.random() * 3000)).map(e => Math.random() > .5 ? true : false)); } for (let sort in sorts) { let s = sorts[sort]; if (s !== sorts.isSorted && s !== sorts.radix) { for (let test of testArrs) { if (s(test).toString() !== test.sort().toString()) { throw new Error(`${sort} failed at sorting strings in ${test}, Expected: ${test.sort().toString()} Actual: ${s(test).toString()}`); } } console.log(`${sort} w/ booleans O K`); } else if (s === sorts.radix) { console.log('Radix does not yet support boolean sorting.'); } } }); it('should be able to accept a comparator', () => { for (let i = 0; i < 20; i ++) { testArrs.push(ranArray().map(e => Object.assign({}, {test: e}))); } for (let sort in sorts) { let s = sorts[sort]; if (s !== sorts.isSorted && s !== sorts.radix) { for (let test of testArrs) { if (s(test, (a,b) => a.test-b.test).toString() !== test.sort().toString()) { throw new Error(`${sort} failed at sorting strings in ${test}, Expected: ${test.sort().toString()} Actual: ${s(test).toString()}`); } } console.log(`${sort} w/ comparator O K`); } else if (s === sorts.radix) { console.log('Radix does not yet support comparators for non-numerical values.'); } } }); }); });