im客户端生成消息序列号算法

JavaScript/前端
357
0
0
2022-09-27
<script> 
    let Identity = (function () {
        let instantiated;
        let spin = 0;
        let mapping = [
            '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
            'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        ];

        function init() {
            //随机一下,确保同一毫秒内,每个客户端的自旋开始值不一样,减少冲突
            spin = Math.floor(Math.random() * 4095);
            return {
                generate: function (type, room_id) {
                    let millisecond = (new Date()).getTime();
                    let current_spin = spin++;
                    if (current_spin > 4095) {
                        spin = 0;
                        current_spin = spin++;
                    }
                    let a = millisecond.toString(2).padStart(42, '0');
                    let b = current_spin.toString(2).padStart(12, '0');
                    let c = type.toString(2).padStart(4, '0');
                    let d = room_id.toString(2).padStart(32, '0');
                    let s = a + b + c + d;
                    let ret = [];
                    for (let i = 0; i < 90;) {
                        ret.push(mapping[parseInt(s.substr(i, 5), 2)]);
                        i += 5;
                    }
                    return ret.join('');
                }
            };
        }

        return {
            getInstance: function () {
                if (!instantiated) {
                    instantiated = init();
                }
                return instantiated;
            }
        }
    })();
    Identity.getInstance();
    let arr = [];
    let un = new Map();
    for (let i = 0; i < 4096 * 10; i++) {
        let tmp = Identity.getInstance().generate(1, 2);
        un.set(tmp, true);
        arr.push(tmp);
    }
    console.log(un.size === arr.length ? '没有重复' : '有重复');
    for (let i = 0; i < arr.length; i++) {
        if (i + 1 < arr.length && arr[i] > arr[i + 1]) {
            console.log('异常的大小', arr[i], arr[i + 1]);
        }
    }    
</script>