Skip to content

Commit

Permalink
feat(random): add IRandom.minmaxUint()
Browse files Browse the repository at this point in the history
- clarify .minmaxInt() is for signed (i32)
- new .minmaxUint() is for unsigned (u32)
- add ARandom.minmaxUint()
  • Loading branch information
postspectacular committed Aug 11, 2023
1 parent 770dbe5 commit 6558eb1
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
12 changes: 11 additions & 1 deletion packages/random/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export interface IRandom extends INorm {
*/
minmax(min: number, max: number): number;
/**
* Returns int in [min..max) interval.
* Returns int in **signed** integer [min..max) interval.
*
* @remarks
* See: https://github.com/thi-ng/umbrella/wiki/Glossary#interval
Expand All @@ -64,6 +64,16 @@ export interface IRandom extends INorm {
* @param max -
*/
minmaxInt(min: number, max: number): number;
/**
* Returns int in **unsigned** integer [min..max) interval.
*
* @remarks
* See: https://github.com/thi-ng/umbrella/wiki/Glossary#interval
*
* @param min -
* @param max -
*/
minmaxUint(min: number, max: number): number;
}

export interface ISeedable<T> {
Expand Down
8 changes: 6 additions & 2 deletions packages/random/src/arandom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ export abstract class ARandom implements IRandom {

minmaxInt(min: number, max: number) {
min |= 0;
max |= 0;
return min + ((this.float() * (max - min)) | 0);
return min + (this.int() % ((max | 0) - min));
}

minmaxUint(min: number, max: number) {
min >>>= 0;
return min + (this.int() % ((max >>> 0) - min));
}
}
2 changes: 1 addition & 1 deletion packages/random/src/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const random = Math.random;
*/
export class SystemRandom extends ARandom {
int() {
return (random() * 4294967296) /* 2**32 */ >>> 0;
return (random() * 0x1_0000_0000) /* 2**32 */ >>> 0;
}

float(norm = 1) {
Expand Down

0 comments on commit 6558eb1

Please sign in to comment.