yaogengzhu / daily-share

个人博客记录、内容在issues
30 stars 4 forks source link

代码片段更新(2021-11-24) #145

Open yaogengzhu opened 2 years ago

yaogengzhu commented 2 years ago

颜色RGB转十六进制

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 51, 255); 
// Result: #0033ff

计算2个日期之间相差多少天

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)

dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366

清除全部Cookie

const clearCookies = document.cookie
    .split(';')
    .forEach(
        (cookie) =>
            (document.cookie = cookie
                .replace(/^ +/, '')
                .replace(
                    /=.*/,
                    `=;expires=${new Date(0).toUTCString()};path=/`
                ))
    );
yaogengzhu commented 2 years ago

将File转换成base64

// 利用FildReader 得到文件的base64
/**
 * FileReader.readAsDataURL()开始读取指定的Blob中的内容。
 * 一旦完成,result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容。
 * **/
const getFileBase64 = (file) => {
    return new Promise((resolve) => {
        let fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = (e) => {
            resolve(e.target.result);
        };
    });
};
yaogengzhu commented 2 years ago

常见的一些判断条件

const opt = Object.prototype.toString;

export function isArray(obj: any): obj is any[] {
  return opt.call(obj) === '[object Array]';
}

export function isObject(obj: any): obj is { [key: string]: any } {
  return opt.call(obj) === '[object Object]';
}

export function isString(obj: any): obj is string {
  return opt.call(obj) === '[object String]';
}

export function isNumber(obj: any): obj is number {
  return opt.call(obj) === '[object Number]' && obj === obj; // eslint-disable-line
}

export function isRegExp(obj: any) {
  return opt.call(obj) === '[object RegExp]';
}

export function isFile(obj: any): obj is File {
  return opt.call(obj) === '[object File]';
}

export function isBlob(obj: any): obj is Blob {
  return opt.call(obj) === '[object Blob]';
}

function isHex(color) {
  return /^#[a-fA-F0-9]{3}$|#[a-fA-F0-9]{6}$/.test(color);
}

function isRgb(color) {
  return /^rgb\((\s*\d+\s*,?){3}\)$/.test(color);
}

function isRgba(color) {
  return /^rgba\((\s*\d+\s*,\s*){3}\s*\d(\.\d+)?\s*\)$/.test(color);
}
export function isColor(color: any): boolean {
  return isHex(color) || isRgb(color) || isRgba(color);
}
export function isUndefined(obj: any): obj is undefined {
  return obj === undefined;
}

export function isFunction(obj: any): obj is (...args: any[]) => any {
  return typeof obj === 'function';
}

export function isEmptyObject(obj: any): boolean {
  return isObject(obj) && Object.keys(obj).length === 0;
}

export function isExist(obj: any): boolean {
  return obj || obj === 0;
}

export function isWindow(el: any): el is Window {
  return el === window;
}
yaogengzhu commented 2 years ago

计算字符串长度,中文字符占两个长度

export default function (str: string): number {
  let len = 0;
  for (let i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
      len += 2;
    } else {
      len++;
    }
  }
  return len;
}
yaogengzhu commented 2 years ago
// 找到树的深度
export function getTreeDeep(treeData: any[], childrenName = 'children') {
  const walker = (tree: any[]) => {
    let deep = 0
    tree.forEach(item => {
      if (item[childrenName]) {
        deep = Math.max(deep, walker(item[childrenName]) + 1)
      } else {
        deep = Math.max(deep, 1)
      }
    })
    return deep
  }

  return walker(treeData)
}
yaogengzhu commented 2 years ago

// 树形结构---- 权限处理

/**
 * 根据权限获取菜
 * menuList 原来的菜单
 * menusKeyList ['', ''] // 菜单中的key
 * @param {*} list 
 */
 static getMenuByPrivilegeList(menuList, menusKeyList){
    return menuList
        .filter((item) => {
            return ( menusKeyList.includes(item.key) || !item.hasPermission) // 判断权限的key是否存在menuList中
        })
        .map((item) => {
            item = Object.assign({}, item)
            if (item.children) {
                item.children = Tools.getMenuByPrivilegeList(item.children, menusKeyList)
            }
            return item
        })
}
/**
 * 菜单树形结构转换
 * @param {*} list 
 * @returns 
 */
static listTransfromToTree = (list) => {
    const tree = []
    for (const node of list) {
        // 如果没有pid就可以认为是根节点
        if (node.parentId === '0') {
            let p = { ...node }
            p.children = getChildren(p.id, list)
            tree.push(p)
        }
    }
    function getChildren(id, list) {
        const children = []
        for (const node of list) {
            if (node.parentId === id) {
                children.push(node)
            }
        }
        for (const node of children) {
            const children = getChildren(node.id, list)
            if (children.length) {
                node.children = children
            }
        }
        return children
    }
    return tree
}