How to generate short uid like “aX4j9Z” (in JS)

前端 未结 10 1587
鱼传尺愫
鱼传尺愫 2020-12-12 14:47

For my web application (in JavaScript) I want to generate short guids (for different objects - that are actually different types - strings and arrays of strings)

I w

10条回答
  •  一个人的身影
    2020-12-12 15:23

    The following generates 62^3 (238,328) unique values of 3 characters provided case sensitivity is unique and digits are allowed in all positions. If case insensitivity is required, remove either upper or lower case characters from chars string and it will generate 35^3 (42,875) unique values.

    Can be easily adapted so that first char is always a letter, or all letters.

    No dobut it can be optimised, and could also refuse to return an id when the limit is reached.

    var nextId = (function() {
      var nextIndex = [0,0,0];
      var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
      var num = chars.length;
    
      return function() {
        var a = nextIndex[0];
        var b = nextIndex[1];
        var c = nextIndex[2];
        var id = chars[a] + chars[b] + chars[c];
    
        a = ++a % num;
    
        if (!a) {
          b = ++b % num; 
    
          if (!b) {
            c = ++c % num; 
          }
        }
        nextIndex = [a, b, c]; 
        return id;
      }
    }());
    

提交回复
热议问题