# JS - 常用代码片段

# 1. 计算文本的宽度

class CommonUtil {
  canvas: HTMLCanvasElement | null = null;
  
  // 计算文本的宽度
  calcTextWidth(text: string, font = '12px Arial') {
    let width = this.calcTextWidthByCanvas(text, font);

    if (width == null) {
      width = this.calcTextWidthByCss(text, font);
    }

    return width;
  }


  // 基于 canvas 计算文本的宽度
  calcTextWidthByCanvas(text: string, font: string) {
    if (this.canvas == null) {
      this.canvas = document.createElement('canvas');
    }
    const context = this.canvas.getContext('2d');

    if (!context) {
      return null;
    }

    context.font = font;
    const metrics = context.measureText(text);

    return metrics.width;
  }

  calcTextWidthByCss(text: string, font: string) {
    const span = document.createElement('span');
    span.style.font = font;
    span.style.visibility = 'hidden';
    span.style.position = 'absolute';
    span.style.left = '0px';
    span.style.top = '0px';
    span.textContent = text;
    document.body.appendChild(span);
    const width = window.getComputedStyle(span)['inline-size'];
    document.body.removeChild(span);
    return parseFloat(width);
  }
}

# 2. 对象深拷贝

通过递归深拷贝一个对象(或数组)

function deepClone(target: any): any {
  if (Array.isArray(target)) {
    return target.map((item) => deepClone(item));
  }

  if (typeof target === 'object' && target !== null) {
    const clone: { [key: string]: any } = {};

    const keys = Reflect.ownKeys(target) as string[];

    for (let i = 0; i < keys.length; i += 1) {
      const key = keys[i];
      clone[key] = deepClone(target[key]);
    }

    return clone;
  }

  return target;
}

参考:

本章目录