Commit acaa546bf1ec74054ac72e2fee1a9eedd8b41759

Authored by 王强
1 parent 52c6f16f

添加 工具文件-onlyKey.ts,生成唯一标识;

Showing 1 changed file with 68 additions and 0 deletions
src/utils/onlyKey.ts 0 → 100644
  1 +/*
  2 + * @Date: 2021-12-23 09:49:48
  3 + * @LastEditors: wangqiang@feewee.cn
  4 + * @LastEditTime: 2022-09-28 14:54:27
  5 + */
  6 +const onlyKeyArray: { [length: number]: string[] } = {};
  7 +const source_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
  8 +
  9 +interface GenerateOptions {
  10 + prefix?: string; // 唯一码前缀
  11 +}
  12 +
  13 +/**
  14 + * @description: 生成唯一key
  15 + * @param {number} length key的长度,默认为8
  16 + * @param {GenerateOptions} options
  17 + * @return {string}
  18 + */
  19 +function generateOnlyKey(length: number = 8, options?: GenerateOptions): string {
  20 + let result = '';
  21 + if (options?.prefix) {
  22 + result = options.prefix + result;
  23 + length -= options.prefix.length;
  24 + }
  25 + const _length = source_string.length - 1;
  26 + for (let i = 0; i < length; i++) {
  27 + //根据指定长度生成随机字符串
  28 + // eslint-disable-next-line radix
  29 + const n = parseInt(`${Math.random() * _length}`); //获取随机数字
  30 + result += source_string[n]; //映射成字符串
  31 + }
  32 + if (onlyKeyArray[length] && onlyKeyArray[length].includes(result)) {
  33 + return generateOnlyKey(length);
  34 + }
  35 + if (onlyKeyArray[length]) {
  36 + onlyKeyArray[length].push(result);
  37 + } else {
  38 + onlyKeyArray[length] = [result];
  39 + }
  40 + return result; //返回映射后的字符串
  41 +}
  42 +
  43 +/**
  44 + * @description: 初始化唯一key对应长度数组,
  45 + * @description: 例如发布工作时,会有从草稿进来的工作,原本就有很多唯一key在上次生成,
  46 + * 如果重新编辑草稿,则需要将那些已经生成的唯一key初始化进来,
  47 + * 不然可能造成新生成的key和之前生成的key一样,导致数据逻辑判断错误,造成数据错乱
  48 + * @param {number} length key的长度
  49 + * @param {string} array 初始化key数组
  50 + */
  51 +function initOnlyKeyArray(length: number, array: string[]) {
  52 + onlyKeyArray[length] = [...new Set(array)];
  53 +}
  54 +
  55 +/**
  56 + * @description: 删除对应长度的唯一key数组
  57 + * @description: 主要用于在某个页面使用完以后,清空对应长度的数组
  58 + * @param {number} length key的长度
  59 + */
  60 +function deleteOnlyKey(length: number) {
  61 + delete onlyKeyArray[length];
  62 +}
  63 +
  64 +export default {
  65 + generateOnlyKey,
  66 + initOnlyKeyArray,
  67 + deleteOnlyKey,
  68 +};
... ...