Skip to content

Commit

Permalink
new function sort3i
Browse files Browse the repository at this point in the history
  • Loading branch information
andrasq committed Mar 15, 2020
1 parent d994f23 commit 4d3838c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,11 @@ Return an array containing the 3 items in ascending order. Much faster than `[a
qibl.sort3(3, 1, 2);
// => [1, 2, 3]

### qibl.sort3i( array, i, j, k )

Rearrange the array contents at offsets i, j and k so that array[i], array[j] and array[k]
are in ascending order.

### qibl.newBuf( arg, encodingOrOffset, length )

Construct a Buffer like `new Buffer()` used to before it was deprecated. Note that with
Expand Down Expand Up @@ -424,7 +429,7 @@ else a Buffer for Buffer data. The callback is invoked when the 'end' event is
Changelog
---------

- 1.6.0 - new function `entries`, new undocumented function `str_locate`, fix get/setIterator property name,
- 1.6.0 - new function `entries`, `sort3i`, new undocumented function `str_locate`, fix get/setIterator property name,
speed up iterators
- 1.5.1 - fix getProperty, do not prevent multiple callbacks from readBody
- 1.5.0 - new functions `derive`, `varargsRenamed`, `isMethodContext`, `readBody`;
Expand Down
9 changes: 9 additions & 0 deletions qibl.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ var qibl = module.exports = {
subsample: subsample,
qsearch: qsearch,
sort3: sort3,
sort3i: sort3i,
curry: curry,
once: once,
tryRequire: tryRequire,
Expand Down Expand Up @@ -321,6 +322,14 @@ function sort3( a, b, c ) {
// descending:
// return (b > a) ? sort3(b, a, c) : (c > a ? [c, a, b] : c > b ? [a, c, b] : [a, b, c]);
}
function sort3i( arr, i, j, k ) {
if (arr[j] < arr[i]) { swapi(arr, i, j); sort3i(arr, i, j, k) }
if (arr[k] < arr[i]) { var t = arr[k]; arr[k] = arr[j]; arr[j] = arr[i]; arr[i] = t; return }
if (arr[k] < arr[j]) swapi(arr, j, k);
}
function swapi( a, i, j ) {
var t = a[i]; a[i] = a[j]; a[j] = t;
}

// See also `qprintf`.
function str_repeat( str, n ) {
Expand Down
11 changes: 11 additions & 0 deletions test-qibl.js
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,17 @@ module.exports = {
t.done();
},

'sort3i': function(t) {
for (var i = 0; i < 1000; i++) {
var arr = [Math.random(), Math.random(), Math.random()];
qibl.sort3i(arr, 0, 1, 2);
t.ok(arr[0] <= arr[1] && arr[1] <= arr[2], "not sorted: " + arr);
qibl.sort3i(arr, 2, 1, 0);
t.ok(arr[0] >= arr[1] && arr[1] >= arr[2], "not sorted: " + arr);
}
t.done();
},

'str_repeat should repeat': function(t) {
var tests = [
[ "", 2, "" ],
Expand Down

0 comments on commit 4d3838c

Please sign in to comment.