Skip to content

Commit 9c407fa

Browse files
author
Alexander Belov
committed
Fixes
1 parent 14c445a commit 9c407fa

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// tslint:disable:no-expression-statement
2+
import test from 'ava';
3+
import { nearestHighestPowerOfTwoResult } from './nearest-highest-power-of-two-result';
4+
5+
test('exponentiation of nearest highest power of two', t => {
6+
const tests = [
7+
[1, 2 ** 0],
8+
[2, 2 ** 1],
9+
[3, 2 ** 2],
10+
[5, 2 ** 3],
11+
[11, 2 ** 4],
12+
[1023, 2 ** 10],
13+
[1024, 2 ** 10],
14+
[1025, 2 ** 11],
15+
[2 ** 31 - 1, 2 ** 31],
16+
[2 ** 78 - 1, 2 ** 78]
17+
];
18+
19+
for (const v of tests) {
20+
const [value, power] = v;
21+
22+
t.is(nearestHighestPowerOfTwoResult(value), power);
23+
}
24+
});
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* Returns the result of exponentiation
3+
* 2 ^ (nearest highest power of two from specific number)
4+
*
5+
* Produces better performance than 2 ^ nearestHighestPowerOfTwo(v) in average
6+
*
7+
* @link http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
8+
*
9+
* @param {number} v
10+
* @returns {number}
11+
*/
12+
export function nearestHighestPowerOfTwoResult(v: number): number {
13+
v--;
14+
v |= v >> 1;
15+
v |= v >> 2;
16+
v |= v >> 4;
17+
v |= v >> 8;
18+
v |= v >> 16;
19+
return ++v;
20+
}

0 commit comments

Comments
 (0)