uuid.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. /** A UUID, either standard 36 characters or 22 characters base64 encoded. */
  8. type UUID = string & { '@type': 'uuid' }
  9. namespace UUID {
  10. const _btoa = typeof btoa !== 'undefined' ? btoa : (s: string) => Buffer.from(s).toString('base64');
  11. const chars: string[] = [];
  12. /** Creates a 22 characters 'base64' encoded UUID */
  13. export function create22(): UUID {
  14. let d = (+new Date()) + now();
  15. for (let i = 0; i < 16; i++) {
  16. chars[i] = String.fromCharCode((d + Math.random() * 0xff) % 0xff | 0);
  17. d = Math.floor(d / 0xff);
  18. }
  19. return _btoa(chars.join('')).replace(/\+/g, '-').replace(/\//g, '_').substr(0, 22) as UUID;
  20. }
  21. export function createv4(): UUID {
  22. let d = (+new Date()) + now();
  23. const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24. const r = (d + Math.random() * 16) % 16 | 0;
  25. d = Math.floor(d / 16);
  26. return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  27. });
  28. return uuid as any;
  29. }
  30. export function is(x: any): x is UUID {
  31. return typeof x === 'string';
  32. }
  33. }
  34. export { UUID };