Skip to content

Commit 22bdddd

Browse files
✨ feat(sortInt16): First draft.
Fixes #9.
1 parent 4d636bc commit 22bdddd

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/array/api/sortInt16.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import sortUint16 from './sortUint16';
2+
3+
const sortInt16 = (array) => {
4+
const shift = -(2 ** 15);
5+
// TODO avoid copying back and forth
6+
const data = Array.prototype.map.call(array, (x) => x - shift);
7+
const output = sortUint16(data);
8+
return Array.prototype.map.call(output, (x) => x + shift);
9+
};
10+
11+
export default sortInt16;

test/src/api/sortInt16.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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 sortInt16 from '../../../src/array/api/sortInt16';
7+
8+
const macro = (t, data) => {
9+
const result = sortInt16(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 || `sortInt16(${repr(data)})`;
20+
21+
test(macro, []);
22+
test(macro, [1, -2, -3, 4]);
23+
24+
const N = 1 << 17;
25+
const longShuffledInput = list(
26+
Int16Array.from(range((-N / 2) | 0, (N / 2) | 0))
27+
);
28+
shuffle(longShuffledInput, 0, N);
29+
test(macro, longShuffledInput);
30+
31+
const longRandomInput = list(
32+
map(() => randrange(-(2 ** 15), 2 ** 15), range(N))
33+
);
34+
test(macro, longRandomInput);

0 commit comments

Comments
 (0)