Skip to content

Commit 4b13233

Browse files
✨ feat: Implement sortInt32.
1 parent 64920d1 commit 4b13233

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/array/api/sortInt32.js

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

test/src/api/sortInt32.js

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

0 commit comments

Comments
 (0)