      1 /**
      2  * Generate a random uuid.
      3  * Written by https://www.broofa.com (robert@broofa.com)
      4  *
      5  * Copyright (c) 2010 Robert Kieffer
      6  * Dual licensed under the MIT and GPL licenses.
      7  * @returns {String}
      8  * @example
      9  *   var uuid = JXG.Util.genUUID();
     10  *   > uuid = '92329D39-6F5C-4520-ABFC-AAB64544E172'
     11  */
     12
     13 /*global JXG: true, define: true*/
     14 /*jslint nomen: true, plusplus: true, bitwise: true*/
     15
     16 import JXG from "../jxg.js";
     17
     18 // constants
     19 var uuidCharsStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
     20     uuidChars = uuidCharsStr.split("");
     21
     22 /**
     23  * General utility routines
     24  * @namespace
     25  */
     26 JXG.Util = JXG.Util || {};
     27
     28 JXG.Util.genUUID = function (prefix) {
     29     var r,
     30         i,
     31         uuid = [],
     32         rnd = 0;
     33
     34     prefix = prefix || "";
     35
     36     if (prefix !== "" && prefix.slice(prefix.length - 1) !== "-") {
     37         prefix = prefix + "-";
     38     }
     39
     40     for (i = 0; i < 36; i++) {
     41         if (i === 8 || i === 13 || i === 18 || i === 23) {
     42             uuid[i] = "-";
     43         } else if (i === 14) {
     44             uuid[i] = "4";
     45         } else {
     46             if (rnd <= 0x02) {
     47                 rnd = (0x2000000 + Math.random() * 0x1000000) | 0;
     48             }
     49
     50             r = rnd & 0xf;
     51             rnd = rnd >> 4;
     52             uuid[i] = uuidChars[i === 19 ? (r & 0x3) | 0x8 : r];
     53         }
     54     }
     55
     56     return prefix + uuid.join("");
     57 };
     58
     59 export default JXG.Util;
     60