2011-12-17 22:52:11 +00:00
|
|
|
/* -*- mode: js2; js2-basic-offset: 4; indent-tabs-mode: nil -*- */
|
|
|
|
|
|
|
|
// Test cases for Util.insertSorted
|
|
|
|
|
|
|
|
// Needed so that Util can bring some UI stuff
|
|
|
|
// we don't actually use
|
2023-07-10 06:05:14 +00:00
|
|
|
import '../../js/ui/environment.js';
|
|
|
|
|
|
|
|
import * as Assertions from '../common/assertions.js';
|
|
|
|
|
2023-07-10 09:53:00 +00:00
|
|
|
import * as Util from '../../js/misc/util.js';
|
2011-12-17 22:52:11 +00:00
|
|
|
|
|
|
|
let arrayInt = [1, 2, 3, 5, 6];
|
2023-07-10 05:58:22 +00:00
|
|
|
Util.insertSorted(arrayInt, 4, (one, two) => one - two);
|
2011-12-17 22:52:11 +00:00
|
|
|
|
2023-07-10 05:56:26 +00:00
|
|
|
Assertions.assertArrayEquals('first test', [1, 2, 3, 4, 5, 6], arrayInt);
|
2011-12-17 22:52:11 +00:00
|
|
|
|
|
|
|
// no comparator, integer sorting is implied
|
|
|
|
Util.insertSorted(arrayInt, 3);
|
|
|
|
|
2023-07-10 05:56:26 +00:00
|
|
|
Assertions.assertArrayEquals('second test', [1, 2, 3, 3, 4, 5, 6], arrayInt);
|
2011-12-17 22:52:11 +00:00
|
|
|
|
2023-07-10 05:59:46 +00:00
|
|
|
let obj1 = {a: 1};
|
|
|
|
let obj2 = {a: 2, b: 0};
|
|
|
|
let obj3 = {a: 2, b: 1};
|
|
|
|
let obj4 = {a: 3};
|
2011-12-17 22:52:11 +00:00
|
|
|
|
|
|
|
let arrayObj = [obj1, obj3, obj4];
|
|
|
|
|
|
|
|
// obj2 compares equivalent to obj3, should be
|
|
|
|
// inserted before
|
2023-07-10 05:58:22 +00:00
|
|
|
Util.insertSorted(arrayObj, obj2, (one, two) => one.a - two.a);
|
2011-12-17 22:52:11 +00:00
|
|
|
|
2023-07-10 05:56:26 +00:00
|
|
|
Assertions.assertArrayEquals('object test', [obj1, obj2, obj3, obj4], arrayObj);
|
2011-12-17 22:52:11 +00:00
|
|
|
|
2023-07-10 05:58:22 +00:00
|
|
|
const checkedCmp = (one, two) => {
|
|
|
|
if (typeof one != 'number' || typeof two != 'number')
|
2011-12-17 22:52:11 +00:00
|
|
|
throw new TypeError('Invalid type passed to checkedCmp');
|
|
|
|
|
2023-07-10 05:58:22 +00:00
|
|
|
return one - two;
|
|
|
|
};
|
2011-12-17 22:52:11 +00:00
|
|
|
|
|
|
|
let arrayEmpty = [];
|
|
|
|
|
|
|
|
// check that no comparisons are made when
|
|
|
|
// inserting in a empty array
|
|
|
|
Util.insertSorted(arrayEmpty, 3, checkedCmp);
|
|
|
|
|
2011-12-20 20:30:30 +00:00
|
|
|
// Insert at the end and check that we don't
|
|
|
|
// access past it
|
|
|
|
Util.insertSorted(arrayEmpty, 4, checkedCmp);
|
|
|
|
Util.insertSorted(arrayEmpty, 5, checkedCmp);
|
|
|
|
|
2011-12-17 22:52:11 +00:00
|
|
|
// Some more insertions
|
|
|
|
Util.insertSorted(arrayEmpty, 2, checkedCmp);
|
|
|
|
Util.insertSorted(arrayEmpty, 1, checkedCmp);
|
|
|
|
|
2023-07-10 05:56:26 +00:00
|
|
|
Assertions.assertArrayEquals('checkedCmp test', [1, 2, 3, 4, 5], arrayEmpty);
|