UNPKG

core-graphics

Version:

A core library for creating shape-based graphic editors

51 lines (50 loc) 2.08 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var getUniquiId = function () { // Modeled after base64 web-safe chars, but ordered by ASCII. var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; // Timestamp of last push, used to prevent local collisions if you push twice in one ms. var lastPushTime = 0; // We generate 72-bits of randomness which get turned into 12 characters and appended to the // timestamp to prevent collisions with other clients. We store the last characters we // generated because in the event of a collision, we'll use those same characters except // "incremented" by one. var lastRandChars = []; return function () { var now = new Date().getTime(); var duplicateTime = now === lastPushTime; lastPushTime = now; var timeStampChars = new Array(8); for (var i = 7; i >= 0; i--) { timeStampChars[i] = PUSH_CHARS.charAt(now % 64); // NOTE: Can't use << here because javascript will convert to int and lose the upper bits. now = Math.floor(now / 64); } if (now !== 0) { throw new Error('We should have converted the entire timestamp.'); } var id = timeStampChars.join(''); if (!duplicateTime) { for (var _i = 0; _i < 4; _i++) { lastRandChars[_i] = Math.floor(Math.random() * 64); } } else { // If the timestamp hasn't changed since last push, use the same random number, except incremented by 1. var _i2 = void 0; for (_i2 = 3; _i2 >= 0 && lastRandChars[_i2] === 63; _i2--) { lastRandChars[_i2] = 0; } lastRandChars[_i2]++; } for (var _i3 = 0; _i3 < 4; _i3++) { id += PUSH_CHARS.charAt(lastRandChars[_i3]); } if (id.length !== 12) { throw new Error('Length should be 12.'); } return id; }; }(); exports.default = getUniquiId;