项目中js功能小结

直接上代码喽

/**
 * 使用闭包和展开运算符将参数数组映射到函数的输入。
 */
const spreadOver = fn => (argsArr = fn(...argsArr));
//  例子
const arrayMax = spreadOver(Math.max);
arrayMax([1, 2, 3]); // -> 3
arrayMax([1, 2, 4]); // -> 4

/* 
* 把一个数组分成指定大小的小数组
* arr:  拆分的数组参数
* size:  小数组个数
*/
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]]

/*
* 数组去重
*/
const valuesofArray = arr => [...new Set(arr)];
// valuesofArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]

/*
* 返回两个数组中不一样的元素
*/
const symmetricDifference = (a, b) => {
  const sA = new Set(a),
    sB = new Set(b);
  return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
};
// symmetricDifference([1,2,3], [1,2,4]) -> [3,4]

/*
  * 获取网站的url
  */
const currentURL = () => window.location.href;
// currentUrl() -> 'https://google.com'

/*
*  返回指定URL参数对象
*/
const getURLParameters = url =>
  url
    .match(/([^?=&]+)(=([^&]*))/g)
    .reduce(
      (a, v) => (
        (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
      ),
      {}
    );
// getURLParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}

/*
* 返回顶部 (平滑返回顶部)
*/
const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};
// scrollToTop()

/*
  * 将数字四舍五入到指定的数字位数。
  */

const round = (n, decimals = 0) =>
  Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
// round(1.005, 2) -> 1.01

/*
* 将消息转换成语音
* 使用SpeechSynthesisUtterance.voice和window.speechSynthesis.getVoices()将消息转换为语音。使用window.speechSynthesis.speak()播放消息。
* API文档请看下面的链接
* https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance
*/
const speechSynthesis = message => {
  const msg = new SpeechSynthesisUtterance(message);
  msg.voice = window.speechSynthesis.getVoices()[0];
  window.speechSynthesis.speak(msg);
};
// speechSynthesis('你试试看久知道了哦')

/*
  * 将json写入文件
  */
const fs = require("fs");
const JSONToFile = (obj, filename) =>
  fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
// JSONToFile({test: "is passed"}, 'testJsonFile') -> 将对象卸入到 'testJsonFile.json'文件

/*
* 大写字符串的第一个字母
*/
const capitalize = ([first, ...rest], lowerRest = false) =>
  first.toUpperCase() +
  (lowerRest ? rest.join("").toLowerCase() : rest.join(""));
// capitalize('myName') -> 'MyName'
// capitalize('myName', true) -> 'Myname'

/*
* 将字符串中每个单词的首字母大写。
*/
const capitalizeEveryWord = str =>
  str.replace(/\b[a-z]/g, char => char.toUpperCase());
// capitalizeEveryWord('hello world!') -> 'Hello World!'

/*
* 颠倒字符串
*/
const reverseString = str =>
  str
    .split("")
    .reverse()
    .join("");
// reverseString('foobar') -> 'raboof'

/*
* 截断一个字符串到指定的长度。
*/
const truncateString = (str, num) =>
  str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + "..." : str;
// truncateString('boomerang', 7) -> 'boom...'

/*
* 生成一个uuid
* 可在需要添加唯一行地方使用
*/
const UUIDGenerator = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );
// UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'

export {
  arrayMax,
  chunk,
  valuesofArray,
  symmetricDifference,
  currentURL,
  symmetricDifference,
  getURLParameters,
  scrollToTop,
  round,
  speechSynthesis,
  truncateString,
  UUIDGenerator
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值