import clone from 'just-clone';
+import Constants from './Constants';
import { WebSocketCloseEventStatusString } from '../types/WebSocket';
export default class Utils {
return sign * (randomPositiveFloat * (max - min) + min);
}
- public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number {
- if (max < min || max < 0 || min < 0) {
- throw new RangeError('Invalid interval');
- }
+ public static getRandomInteger(max = Constants.MAX_RANDOM_INTEGER, min = 0): number {
max = Math.floor(max);
if (!Utils.isNullOrUndefined(min) && min !== 0) {
min = Math.ceil(min);
- return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
+ return Math.floor(crypto.randomInt(min, max + 1));
}
- return Math.floor(Utils.secureRandom() * (max + 1));
+ return Math.floor(crypto.randomInt(max + 1));
}
public static roundTo(numberValue: number, scale: number): number {
setTimeout(() => {
if (Utils.isPromisePending(promise)) {
timeoutCallback();
+ // FIXME: The original promise shall be canceled
}
reject(timeoutError);
}, timeoutMs);
import expect from 'expect';
+import Constants from '../../src/utils/Constants';
import Utils from '../../src/utils/Utils';
describe('Utils test suite', () => {
let randomInteger = Utils.getRandomInteger();
expect(Number.isSafeInteger(randomInteger)).toBe(true);
expect(randomInteger).toBeGreaterThanOrEqual(0);
- expect(randomInteger).toBeLessThanOrEqual(Number.MAX_SAFE_INTEGER);
+ expect(randomInteger).toBeLessThanOrEqual(Constants.MAX_RANDOM_INTEGER);
expect(randomInteger).not.toEqual(Utils.getRandomInteger());
- expect(() => Utils.getRandomInteger(0, 1)).toThrowError(new RangeError('Invalid interval'));
- expect(() => Utils.getRandomInteger(-1)).toThrowError(new RangeError('Invalid interval'));
- expect(() => Utils.getRandomInteger(0, -1)).toThrowError(new RangeError('Invalid interval'));
+ expect(() => Utils.getRandomInteger(0, 1)).toThrowError(
+ 'The value of "max" is out of range. It must be greater than the value of "min" (1). Received 1'
+ );
+ expect(() => Utils.getRandomInteger(-1)).toThrowError(
+ 'The value of "max" is out of range. It must be greater than the value of "min" (0). Received 0'
+ );
+ expect(() => Utils.getRandomInteger(Constants.MAX_RANDOM_INTEGER + 1)).toThrowError(
+ `The value of "max" is out of range. It must be <= ${
+ Constants.MAX_RANDOM_INTEGER + 1
+ }. Received 281_474_976_710_656`
+ );
randomInteger = Utils.getRandomInteger(2, 1);
expect(randomInteger).toBeGreaterThanOrEqual(1);
expect(randomInteger).toBeLessThanOrEqual(2);