uid.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module utils/uid
  7. */
  8. // A hash table of hex numbers to avoid using toString() in uid() which is costly.
  9. // [ '00', '01', '02', ..., 'fe', 'ff' ]
  10. const HEX_NUMBERS = new Array( 256 ).fill()
  11. .map( ( val, index ) => ( '0' + ( index ).toString( 16 ) ).slice( -2 ) );
  12. /**
  13. * Returns a unique id. The id starts with an "e" character and a randomly generated string of
  14. * 32 alphanumeric characters.
  15. *
  16. * **Note**: The characters the unique id is built from correspond to the hex number notation
  17. * (from "0" to "9", from "a" to "f"). In other words, each id corresponds to an "e" followed
  18. * by 16 8-bit numbers next to each other.
  19. *
  20. * @returns {String} An unique id string.
  21. */
  22. export default function uid() {
  23. // Let's create some positive random 32bit integers first.
  24. //
  25. // 1. Math.random() is a float between 0 and 1.
  26. // 2. 0x100000000 is 2^32 = 4294967296.
  27. // 3. >>> 0 enforces integer (in JS all numbers are floating point).
  28. //
  29. // For instance:
  30. // Math.random() * 0x100000000 = 3366450031.853859
  31. // but
  32. // Math.random() * 0x100000000 >>> 0 = 3366450031.
  33. const r1 = Math.random() * 0x100000000 >>> 0;
  34. const r2 = Math.random() * 0x100000000 >>> 0;
  35. const r3 = Math.random() * 0x100000000 >>> 0;
  36. const r4 = Math.random() * 0x100000000 >>> 0;
  37. // Make sure that id does not start with number.
  38. return 'e' +
  39. HEX_NUMBERS[ r1 >> 0 & 0xFF ] +
  40. HEX_NUMBERS[ r1 >> 8 & 0xFF ] +
  41. HEX_NUMBERS[ r1 >> 16 & 0xFF ] +
  42. HEX_NUMBERS[ r1 >> 24 & 0xFF ] +
  43. HEX_NUMBERS[ r2 >> 0 & 0xFF ] +
  44. HEX_NUMBERS[ r2 >> 8 & 0xFF ] +
  45. HEX_NUMBERS[ r2 >> 16 & 0xFF ] +
  46. HEX_NUMBERS[ r2 >> 24 & 0xFF ] +
  47. HEX_NUMBERS[ r3 >> 0 & 0xFF ] +
  48. HEX_NUMBERS[ r3 >> 8 & 0xFF ] +
  49. HEX_NUMBERS[ r3 >> 16 & 0xFF ] +
  50. HEX_NUMBERS[ r3 >> 24 & 0xFF ] +
  51. HEX_NUMBERS[ r4 >> 0 & 0xFF ] +
  52. HEX_NUMBERS[ r4 >> 8 & 0xFF ] +
  53. HEX_NUMBERS[ r4 >> 16 & 0xFF ] +
  54. HEX_NUMBERS[ r4 >> 24 & 0xFF ];
  55. }