uuid.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  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 chars: string[] = [];
  10. /** Creates 22 characted "base64" UUID */
  11. export function create22(): UUID {
  12. let d = (+new Date()) + now();
  13. for (let i = 0; i < 16; i++) {
  14. chars[i] = String.fromCharCode((d + Math.random()*0xff)%0xff | 0);
  15. d = Math.floor(d/0xff);
  16. }
  17. return btoa(chars.join('')).replace(/\+/g, '-').replace(/\//g, '_').substr(0, 22) as UUID;
  18. }
  19. export function createv4(): UUID {
  20. let d = (+new Date()) + now();
  21. const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  22. const r = (d + Math.random()*16)%16 | 0;
  23. d = Math.floor(d/16);
  24. return (c==='x' ? r : (r&0x3|0x8)).toString(16);
  25. });
  26. return uuid as any;
  27. }
  28. }
  29. export default UUID;