Skip to content

Commit

Permalink
Merge pull request #16945 from ckeditor/ck/remove-math-random-from-uid
Browse files Browse the repository at this point in the history
Internal (utils): Remove `Math.random()` from `uid` implementation.
  • Loading branch information
arkflpc authored Aug 20, 2024
2 parents b37bbbf + decf404 commit 01b9275
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
14 changes: 1 addition & 13 deletions packages/ckeditor5-utils/src/uid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,7 @@ const HEX_NUMBERS = new Array( 256 ).fill( '' )
*/
export default function uid(): string {
// Let's create some positive random 32bit integers first.
//
// 1. Math.random() is a float between 0 and 1.
// 2. 0x100000000 is 2^32 = 4294967296.
// 3. >>> 0 enforces integer (in JS all numbers are floating point).
//
// For instance:
// Math.random() * 0x100000000 = 3366450031.853859
// but
// Math.random() * 0x100000000 >>> 0 = 3366450031.
const r1 = Math.random() * 0x100000000 >>> 0;
const r2 = Math.random() * 0x100000000 >>> 0;
const r3 = Math.random() * 0x100000000 >>> 0;
const r4 = Math.random() * 0x100000000 >>> 0;
const [ r1, r2, r3, r4 ] = crypto.getRandomValues( new Uint32Array( 4 ) );

// Make sure that id does not start with number.
return 'e' +
Expand Down
12 changes: 12 additions & 0 deletions packages/ckeditor5-utils/tests/uid.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import uid from '../src/uid.js';

describe( 'utils', () => {
describe( 'uid', () => {
afterEach( () => {
sinon.restore();
} );

it( 'should return different ids', () => {
const id1 = uid();
const id2 = uid();
Expand All @@ -22,5 +26,13 @@ describe( 'utils', () => {
expect( id2 ).to.match( uuidRegex );
expect( id3 ).to.match( uuidRegex );
} );

it( 'should not use Math.random()', () => {
const spy = sinon.spy( Math, 'random' );

uid();

expect( spy.notCalled ).to.be.true;
} );
} );
} );

0 comments on commit 01b9275

Please sign in to comment.