uuid.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { now } from '../mol-util/now';
  7. type UUID = string & { '@type': 'uuid' }
  8. namespace UUID {
  9. const _btoa = typeof btoa !== 'undefined' ? btoa : (s: string) => Buffer.from(s).toString('base64')
  10. const chars: string[] = [];
  11. /** Creates 22 characted "base64" UUID */
  12. export function create22(): UUID {
  13. let d = (+new Date()) + now();
  14. for (let i = 0; i < 16; i++) {
  15. chars[i] = String.fromCharCode((d + Math.random()*0xff)%0xff | 0);
  16. d = Math.floor(d/0xff);
  17. }
  18. return _btoa(chars.join('')).replace(/\+/g, '-').replace(/\//g, '_').substr(0, 22) as UUID;
  19. }
  20. export function createv4(): UUID {
  21. let d = (+new Date()) + now();
  22. const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  23. const r = (d + Math.random()*16)%16 | 0;
  24. d = Math.floor(d/16);
  25. return (c==='x' ? r : (r&0x3|0x8)).toString(16);
  26. });
  27. return uuid as any;
  28. }
  29. }
  30. export default UUID;