Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[No QA] method to randomly generate 64 bit int as string #10436

Merged
merged 17 commits into from
Aug 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/CONST.js
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,8 @@ const CONST = {
INVITE: 'invite',
LEAVE_ROOM: 'leaveRoom',
},
MAX_64BIT_LEFT_HALF: 9_223_372_036,
MAX_64BIT_RIGHT_HALF: 854_775_807,
IOS_KEYBOARD_SPACE_OFFSET: -30,
};

Expand Down
32 changes: 32 additions & 0 deletions src/libs/NumberUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import CONST from '../CONST';

/**
* Generates a random positive 64 bit numeric string by randomly generating the left half and right half and concatenating them. Used to generate client-side ids.
* @returns {String} string representation of a randomly generated 64 bit signed integer
*/
/* eslint-disable no-unused-vars */
function rand64() {
// Max 64-bit signed:
// 9,223,372,036,854,775,807
// The left part of the max 64-bit number *+1* because we're flooring it
const left = Math.floor(Math.random() * (CONST.MAX_64BIT_LEFT_HALF + 1));

// The right part of the max 64-bit number *+1* for the same reason
let right;

// If the top is any number but the highest one, we can actually have any value for the rest
if (left !== CONST.MAX_64BIT_LEFT_HALF) {
right = Math.floor(Math.random() * 1_000_000_000);
} else {
right = Math.floor(Math.random() * (CONST.MAX_64BIT_RIGHT_HALF + 1));
}

// Pad the right with zeros
const rightString = right.toString().padStart(9, '0');

return left + rightString;
}

module.exports = {
rand64,
};
13 changes: 13 additions & 0 deletions tests/unit/NumberUtilsTest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const NumberUtils = require('../../src/libs/NumberUtils');

describe('libs/NumberUtils', () => {
it('should generate a random 64-bit numeric string', () => {
const id = NumberUtils.rand64();
expect(typeof id).toBe('string');
// eslint-disable-next-line no-undef
expect(BigInt(id)).toBeLessThanOrEqual(BigInt(9223372036854775807));
// eslint-disable-next-line no-undef
expect(BigInt(id)).toBeGreaterThanOrEqual(0);
});
});