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

前端 未结 10 1575
鱼传尺愫
鱼传尺愫 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:33

    This will generate a sequence of unique values. It improves on RobG's answer by growing the string length when all values have been exhaused.

    var IdGenerator = (function () {
    
        var defaultCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_-+=[]{};:?/.>,<|".split("");
    
        var IdGenerator = function IdGenerator(charset) {
            this._charset = (typeof charset === "undefined") ? defaultCharset : charset;
            this.reset();
        };
    
        IdGenerator.prototype._str = function () {
            var str = "",
                perm = this._perm,
                chars = this._charset,
                len = perm.length,
                i;
            for (i = 0; i < len; i++) {
                str += chars[perm[i]];
            }
            return str;
        };
    
        IdGenerator.prototype._inc = function () {
            var perm = this._perm,
                max = this._charset.length - 1,
                i;
            for (i = 0; true; i++) {
                if (i > perm.length - 1) {
                    perm.push(0);
                    return;
                } else {
                    perm[i]++;
                    if (perm[i] > max) {
                        perm[i] = 0;
                    } else {
                        return;
                    }
                }
            }
        };
    
        IdGenerator.prototype.reset = function () {
            this._perm = [];
        };
    
        IdGenerator.prototype.current = function () {
            return this._str();
        };
    
        IdGenerator.prototype.next = function () {
            this._inc();
            return this._str();
        };
    
        return IdGenerator;
    
    }).call(null);
    

    Usage:

    var g = new IdGenerator(),
        i;
    
    for (i = 0; i < 100; i++) {
       console.log(g.next());
    }
    

    This gist contains the above implementation and a recursive version.

提交回复
热议问题