Skip to content

Commit 4d636bc

Browse files
✨ feat(sortUint16): First draft.
Fixes #7.
1 parent 298b8fb commit 4d636bc

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/array/api/sortUint16.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import sort from './sort';
2+
3+
const sortUint16 = (array) => {
4+
const k = 2; // TODO make it depend on array.length
5+
const M = 2 ** 8;
6+
// TODO avoid copying back and forth
7+
const tuples = Array.prototype.map.call(array, (x) => [
8+
(x & 0xff00) >>> 8,
9+
(x & 0xff) >>> 0
10+
]);
11+
const output = sort(k, M, tuples);
12+
return Array.prototype.map.call(output, ([c, d]) => ((c << 8) | d) >>> 0);
13+
};
14+
15+
export default sortUint16;

test/src/api/sortUint16.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import test from 'ava';
2+
import {sorted, range, list, map} from '@aureooms/js-itertools';
3+
import {shuffle, randrange} from '@aureooms/js-random';
4+
import {increasing} from '@aureooms/js-compare';
5+
6+
import sortUint16 from '../../../src/array/api/sortUint16';
7+
8+
const macro = (t, data) => {
9+
const result = sortUint16(data.slice());
10+
const expected = sorted(increasing, data);
11+
t.deepEqual(expected, result);
12+
};
13+
14+
const repr = (data) =>
15+
data.length >= 20
16+
? `[${data.slice(0, 9)},..,${data.slice(-9)}]`
17+
: JSON.stringify(data);
18+
19+
macro.title = (title, data) => title || `sortUint16(${repr(data)})`;
20+
21+
test(macro, []);
22+
test(macro, [1, 2, 3, 4]);
23+
24+
const N = 1 << 17;
25+
const longShuffledInput = list(Uint16Array.from(range(N)));
26+
shuffle(longShuffledInput, 0, N);
27+
test(macro, longShuffledInput);
28+
29+
const longRandomInput = list(map(() => randrange(2 ** 16) >>> 0, range(N)));
30+
test(macro, longRandomInput);

0 commit comments

Comments
 (0)