Skip to content

Commit 45b691d

Browse files
committed
add nextPow2
1 parent 118b1de commit 45b691d

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/utils.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,23 @@ export function randomRange(min, max) {
112112
*/
113113
export function randomRangeInt(min, max) {
114114
return Math.floor(this.randomRange(min, max));
115+
}
116+
117+
/**
118+
* Returns the next power of two for the value
119+
*
120+
* @method nextPow2
121+
* @param {number} val
122+
* @return {number} the the next power of two
123+
*/
124+
export function nextPow2(val) {
125+
--val;
126+
val = (val >> 1) | val;
127+
val = (val >> 2) | val;
128+
val = (val >> 4) | val;
129+
val = (val >> 8) | val;
130+
val = (val >> 16) | val;
131+
++val;
132+
133+
return val;
115134
}

test/utils.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,18 @@ tap.test('utils', t => {
7373
t.end();
7474
});
7575

76+
t.test('randomRangeInt', t => {
77+
let r = utils.randomRangeInt(-10, 10);
78+
t.assert(r >= -10 && r <= 10);
79+
t.end();
80+
});
81+
82+
t.test('nextPow2', t => {
83+
t.equal(utils.nextPow2(10), 16);
84+
t.equal(utils.nextPow2(245), 256);
85+
t.end();
86+
});
87+
7688
t.end();
7789
});
7890

0 commit comments

Comments
 (0)