utils工具库函数

88 阅读1分钟

计算文本超过3行

/**
 * compute difference between offsetHeight and lineHeights which includes many lines
 * --Do not need to pay attention to size of screen
 * @param el DOMElement
 * @param lines lines of text (default: 3 lines)
 * @returns boolean
 */
export const computeEleLineHeightByLines = (
  el: Element,
  lines: number = 3
): boolean => {
  const styleObj: CSSStyleDeclaration = window.getComputedStyle(el);
  const lineHeight: number = Number(styleObj?.lineHeight?.replace(/px$/, ''));
  // --support all size of screen including zoom in and out
  return (
    Math.abs((el as HTMLElement).offsetHeight - lineHeight * lines) < lineHeight
  );
};

数组对象去重


/**
 * filter to repeat Object by the second parameter
 * @param sourceArr source array
 * @param key keyword used to filter
 * @returns array including object of no repeat
 */
export const filterRepeatObjectInArrayByKey = <T, K extends keyof T>(
  sourceArr: T[],
  key: K
): T[] => {
  if (!key) return sourceArr;
  if (Array.isArray(sourceArr) && sourceArr?.length === 0) return sourceArr;
  const tempObj: any = {};
  return sourceArr?.reduce((arr: T[], next: T) => {
    !!tempObj[next[key]]
      ? undefined
      : ((tempObj[next[key]] as boolean) = true) && arr.push(next);
    return arr;
  }, []);
};