代码片段

  • pubdate:2020-10-20 14:39:50

  • tags:代码片段


简短而又有用的一些代码片段,一般都是 ts 版本 可以利用 typescript playground 很方便的将 ts 的代码转为 js 的代码然后使用

依赖浏览器 dom

// 复制文本
export const copy = (str: string) => {
  // 第一种 这个在控制台中直接用会报错 Uncaught (in promise) DOMException: Document is not focused.
  navigator.clipboard.writeText(str);
};

export const copy2 = (str: string) => {
  // 第二种 这个可以直接在浏览器控制台内使用
  const input = document.createElement("textarea");
  input.style.opacity = "0";
  document.body.appendChild(input);
  input.value = str;
  input.select();
  const r = document.execCommand("copy");
  input.remove();
  return r;
};

纯粹无依赖

Array

数组求和

/** 数组求和 */
export function ArraySum<T>(arr: T[], f: (el: T) => number) {
  return arr.map(f).reduce((a, b) => a + b, 0);
}

数组取随机 n 个元素

/** 从数组中随机取 n 个元素 */
export function sampleSize<T>([...arr]: T[], n = 1) {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr.slice(0, n);
}

今天(2020-11-17)发现 GitHub 的消息那里的分页也是存在问题的,就是在一开始如果有两页数据一直点已读然后点下一页发现是空的,再点上一页才能看见消息


数组去重 & 求和

/** 数组去重
 * 1. 可以设置函数来决定什么样算重复
 * 2. 可以设置函数来决定遇到重复的结果该怎么合并
 */
export function Array去重<T>(
  arr: T[],
  /** 需要返回该对象的一个唯一标识(需要是原始值 用于和其他的进行比较) */ f: (el: T) => unknown = (el: T) => el,
  /** 用于决定和重复对象的合并方式,默认取后面的值,丢弃旧值 */ mergeF: (a: T, b: T) => T = (a, b) => b,
) {
  let result = [] as T[];
  let label = [] as unknown[];

  for (const el of arr) {
    const id = f(el);
    const i = label.findIndex((el) => el === id);
    if (i !== -1) {
      result[i] = mergeF(result[i], el);
    } else {
      label.push(id);
      result.push(el);
    }
  }

  return result;
}

其他代码片段相关

隐藏滚动条 #代码片段#

.demo::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}

.demo {
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
  overflow-x: hidden;
  overflow-y: auto;
}

vue reactive

useParamsObj 获取 url 参数,以及直接向对象写属性自动转换为 url

by 崮生 from 崮生 • 一些随笔 🎨,欢迎 赞助本文
本文欢迎分享与聚合,全文转载未经授权( 联系我)不许可。