Skip to content

Commit

Permalink
feat: add utilities isPowerOfTwo and nextPowerOfTwo
Browse files Browse the repository at this point in the history
  • Loading branch information
lpatiny committed Nov 23, 2023
1 parent e5677a7 commit bec701a
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/utils/__tests__/isPowerOfTwo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { isPowerOfTwo } from '../..';

test('check if a power of two is next', () => {
expect(isPowerOfTwo(1024)).toEqual(true);
expect(isPowerOfTwo(1025)).toEqual(false);
expect(isPowerOfTwo(1023)).toEqual(false);
});
7 changes: 7 additions & 0 deletions src/utils/__tests__/nextPowerOfTwo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { nextPowerOfTwo } from '../..';

test('check if a power of two is next', () => {
expect(nextPowerOfTwo(1024)).toEqual(1024);
expect(nextPowerOfTwo(1025)).toEqual(2048);
expect(nextPowerOfTwo(1023)).toEqual(1024);
});
2 changes: 2 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ export * from './createFromToArray';
export * from './createRandomArray';
export * from './createStepArray';
export * from './getRescaler';
export * from './isPowerOfTwo';
export * from './nextPowerOfTwo';
7 changes: 7 additions & 0 deletions src/utils/isPowerOfTwo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Check if a number is a power of two
*/

export function isPowerOfTwo(n: number): boolean {
return n !== 0 && (n & (n - 1)) === 0;
}
13 changes: 13 additions & 0 deletions src/utils/nextPowerOfTwo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Get the size of the next power of two
*/
export function nextPowerOfTwo(n: number): number {
if (n === 0) return 1;
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n + 1;
}

0 comments on commit bec701a

Please sign in to comment.