UNPKG

short-uid

Version:

Length Efficient Unique ID Generator

1 lines 1.91 kB
(function(){var ShortUID;ShortUID=function(){var DEFAULT_RANDOM_ID_LEN,DICT_RANGES,dict,dictIndex,dictLength,dictRange,lowerBound,rangeType,upperBound,_i;DEFAULT_RANDOM_ID_LEN=6;DICT_RANGES={digits:[48,58],lowerCase:[97,123],upperCase:[65,91]};dict=[];for(rangeType in DICT_RANGES){dictRange=DICT_RANGES[rangeType];lowerBound=dictRange[0],upperBound=dictRange[1];for(dictIndex=_i=lowerBound;lowerBound<=upperBound?_i<upperBound:_i>upperBound;dictIndex=lowerBound<=upperBound?++_i:--_i){dict.push(String.fromCharCode(dictIndex))}}dict=dict.sort(function(a,b){return Math.random()<=.5});dictLength=dict.length;function ShortUID(options){if(options==null){options={}}this.counter=0;this.debug=options.debug;this.log("Generator created with Dictionary Size "+dictLength)}ShortUID.prototype.log=function(){var _ref;arguments[0]="[frugal-id] "+arguments[0];if(this.debug===true){return typeof console!=="undefined"&&console!==null?(_ref=console.log)!=null?_ref.apply(console,arguments):void 0:void 0}};ShortUID.prototype.getDict=function(){return dict};ShortUID.prototype.counterUUID=function(){var counterDiv,counterRem,id;id="";counterDiv=this.counter;while(true){counterRem=counterDiv%dictLength;counterDiv=parseInt(counterDiv/dictLength);id+=dict[counterRem];if(counterDiv===0){break}}this.counter++;return id};ShortUID.prototype.randomUUID=function(uuidLength){var id,idIndex,randomPartIdx,_j;if(uuidLength==null){uuidLength=DEFAULT_RANDOM_ID_LEN}if(uuidLength==null||uuidLength<1){throw new Error("Invalid UUID Length Provided")}id="";for(idIndex=_j=0;0<=uuidLength?_j<uuidLength:_j>uuidLength;idIndex=0<=uuidLength?++_j:--_j){randomPartIdx=parseInt(Math.random()*dictLength)%dictLength;id+=dict[randomPartIdx]}return id};return ShortUID}();if(typeof window!=="undefined"&&window!==null){window.ShortUID=ShortUID}else if(typeof exports!=="undefined"&&exports!==null){module.exports=ShortUID}}).call(this);