0.1.21 • Published 8 months ago

@tnt-temp/utils v0.1.21

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
8 months ago

@tntd/utils

TNTD前端业务代码工具库 支持TS引用

utils npm download MIT

目的:我们把业务开发中常用的工具类函数,统一封装到@tntd/utils包下,以提高开发效率。

🏗️ 安装使用

$ npm install @tntd/utils
import { getCookie } from "@tntd/utils";

const cookie = getCookie("test");

🌽 按需加载方法1

安装 babel-plugin-import

npm install babel-plugin-import -save-dev

新建 .babelrc 文件,如果有则跳过

{
    "plugins": [
        // 如下是babel-plugin-import插件的配置
        [
            "import", {
                "libraryName": "@tntd/utils",   // 要实现按需加载的库名
                "camel2DashComponentName": false    // 是否要把组件的目录名改成小写形式,即my-button,默认为true
            }, 
            // 如果你的@babel版本低于7,这句配置不用写
            "@tntd/utils"
        ]
    ]
}

🌽 按需加载方法2

安装tntdbabel插件

$ npm install babel-plugin-tntd-utils --save-dev

.babelrc中添加如下配置即可

"plugins": [
    [
      "babel-plugin-tntd-utils",
      {
        "library": ["@tntd/utils"]
      }
    ],
]

📦 API文档

browser

getBrowserName 获取浏览器名称

import { getBrowserName } from '@tntd/utils'
getBrowserName()    // Chrome

getBrowserNameVersion 获取浏览器名称和版本

import { getBrowserNameVersion } from '@tntd/utils'
getBrowserName()    // Chrome: 116.0.0.0

color

tinyColor 颜色处理函数

import { tinyColor } from '@tntd/utils'

api 同 https://www.npmjs.com/package/tinycolor2

common

base64 base64加解密

import { base64 } from '@tntd/utils'
base64.encode('hello world')    // aGVsbG8gd29ybGQ= 
base64.decode('aGVsbG8gd29ybGQ=')    // hello world 
// 更多 api 待补充

bytesToSize 自动转换字节单位

import { bytesToSize } from '@tntd/utils'
bytesToSize(1231773835253)    // 1.12 TB 

compareVersion 比较版本号

import { compareVersion } from '@tntd/utils'
compareVersion('1.1.0','1.2.0')    // -1
compareVersion('1.3.0','1.2.0')    // 1
compareVersion('1.2.0','1.2.0')    // 0
// 版本号可以带 v 或 V
compareVersion('v1.1.0','v1.2.0')    // -1

copy 复制到剪贴板

import { copy } from '@tntd/utils'
copy('Text');
// Copy with options
copy('Text', {
  debug: true,
  message: '复制信息成功',
});

deleteEmptyObjItem 清除对象里面空的属性

import { deleteEmptyObjItem } from '@tntd/utils'

const obj = {
    a: 1,
    b: null,
    c: "",
    d: undefined
};
deleteEmptyObjItem(obj);
// { a: 1 }

generateUUID 唯一ID生成器

import { generateUUID } from '@tntd/utils'
generateUUID();    // 5ee437c3-61cc-46ce-8903-1dbafcb9bb3d

getExtname 获取文件后缀名的方法

import { getExtname } from '@tntd/utils'
getExtname('hello.ppt');    // ppt

getStrLength 获取字符长度,一个汉字算两个长度

import { getStrLength } from '@tntd/utils'
getStrLength('hello同盾');    // 9

getUrlKey 获取URL参数

// 假设当前 url 是 http://localhost:3000?hi=1&fine=jack
import { getUrlKey } from '@tntd/utils'
getUrlKey('fine');    // jack
// 当然你也可以传入url
getUrlKey('school','https://www.baidu.com?age=12&school=浙江大学');    // 浙江大学

queryString Url 参数解析

import { queryString } from '@tntd/utils'

console.log(location.search);
//=> '?foo=bar'

const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}

console.log(location.hash);
//=> '#token=bada55cafe'

const parseUrlResult=queryString.parseUrl(location.href)
// or 不填则默认是当前location.href
const parseUrlResult=queryString.parseUrl()
console.log(parseUrlResult)
//=> {foo: 'bar'}

const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}

parsed.foo = 'unicorn';
parsed.ilike = 'pizza';

const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'

location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'

safeParseJSON 安全转化 JSON

import { safeParseJSON } from '@tntd/utils'

const str = "{name: 1, age: null}";
const defaultObj = {name: 1};
safeParseJSON(str, defaultObj);

saveAs 纯前端下载文件或图片

import { saveAs } from '@tntd/utils'

// 出于兼容性考虑:下载内容小于500M

// 文件下载  saveAs(blob, fileName)
const blob = new Blob(["Hello, world!"], { type: "text/plain;charset=utf-8" });
saveAs(blob, "hello world.txt");

const data = {
 a: 1,
 b: {
   c: 2
 }
};
const blob = new Blob([JSON.stringify(data)]);
saveAs(blob, "data.json");

// 图片下载 saveAs(url, fileName)
// 注意:url只有同源情况下才会在当前页面下载,否则新开窗口,同时支持base64图片下载
saveAs("https://sinan.tongdun.me/cdn/bucket/article/135/20865/20200308214806320_image.png", "image.png");

// 支持canvas导出图片
let canvas = document.getElementById("Mycanvas");
canvas.toBlob(function (blob) {
    saveAs(blob, "image.png");
});

trim 删除字符串首尾空格或特定字符

import { trim } from '@tntd/utils'

trim(' abc  '); //-> 'abc'
trim('_abc_','_'); //-> 'abc'
trim('_abc_',['a','c','_']); //-> 'b'

convert

base64ToBlob 将base64转换为Blob

import { base64ToBlob } from '@tntd/utils'

// TODO

base64ToFile 将base64转换为File

import { base64ToFile } from '@tntd/utils'

// TODO

blobToFile 将 Blob 转换为 File

import { blobToFile } from '@tntd/utils'

// TODO

flatToTree 将扁平数组转换为树形对象

import { flatToTree } from '@tntd/utils'

const flatList=[
    {
        "name": "合肥",
        "parentCode": "340000",
        "code": "340100"
    },
    {
        "name": "芜湖",
        "parentCode": "340000",
        "code": "340200"
    },
    {
        "name": "安徽",
        "code": "340000"
    },
    {
        "name": "福州",
        "parentCode": "350000",
        "code": "350100"
    },
    {
        "name": "厦门",
        "parentCode": "350000",
        "code": "350200"
    },
    {
        "name": "福建",
        "code": "350000"
    }
]
flatToTree(flatList, {idName:'code', pidName:'parentCode', childrenName:'city'})

numberToChinese 数字转汉字

import { numberToChinese } from '@tntd/utils'
numberToChinese(1234888)    // 一百二十三萬四仟八百八十八

numberToCnMoney 数字转大写金额

import { numberToCnMoney } from '@tntd/utils'
numberToCnMoney(1234888)    // 壹佰贰拾叁万肆仟捌佰捌拾捌元整

/**

  • @desc 参数:pinyin(string[, separator, lowerCase])
  • @param {str} string 要转换的字符
  • @return {separator} string 分隔符
  • @return {lowerCase} boolean 是否小写,默认小写 */

pinyin('我们和他们') // womenhetamen pinyin('我们和他们','-') // wo-men-he-ta-men pinyin('我们和他们','-',false) // WO-MEN-HE-TA-MEN

```toThousands``` 千分位分隔符  
```js
import { toThousands } from '@tntd/utils'
toThousands(16636234)       // 16,636,234

treeToFlat 将树形结构数据转换为扁平数组

import { treeToFlat } from '@tntd/utils'

const dataTree=[
  {
    "name": "安徽",
    "city": [
      {
        "name": "合肥",
        "parentCode": "340000",
        "code": "340100"
      },
      {
        "name": "芜湖",
        "parentCode": "340000",
        "code": "340200"
      }
    ],
    "code": "340000"
  },
  {
    "name": "福建",
    "city": [
      {
        "name": "福州",
        "parentCode": "350000",
        "code": "350100"
      },
      {
        "name": "厦门",
        "parentCode": "350000",
        "code": "350200"
      }
    ],
    "code": "350000"
  }
]
treeToFlat(dataTree,'city')  // convertToFlat 第二个参数是层级列表 key 名称,默认是 children

cookie

getCookie 根据name读取cookie

import { getCookie } from '@tntd/utils'
getCookie('test')

removeCookie 根据name删除cookie

import { removeCookie } from '@tntd/utils'
removeCookie('test')

setCookie 设置Cookie

import { setCookie } from '@tntd/utils'
setCookie("test", "123", 3)

functional

debounce 防抖动函数

import { debounce } from '@tntd/utils'

// 避免窗口在变动时出现昂贵的计算开销。
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 
// 当点击时 `sendMail` 随后就被调用。
jQuery(element).on('click', _.debounce(sendMail, 300, {
  'leading': true,
  'trailing': false
}));
 
// 确保 `batchLog` 调用1次之后,1秒内会被触发。
var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
 
// 取消一个 trailing 的防抖动调用
jQuery(window).on('popstate', debounced.cancel);

throttle 节流函数

import { throttle } from '@tntd/utils'

// 避免在滚动时过分的更新定位
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
 
// 点击后就调用 `renewToken`,但5分钟内超过1次。
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
 
// 取消一个 trailing 的节流调用。
jQuery(window).on('popstate', throttled.cancel);

judge

isEmptyObject 判断obj是否为空

import { isEmptyObject } from '@tntd/utils'
isEmptyObject({})    // true  

isJSON 判断字符串是否为json

import { isJSON } from '@tntd/utils'
isJSON('{}')    // true  

operation

accAdd 两个浮点数求和

import { accAdd } from '@tntd/utils'
accAdd(2.3122, 3.234123);
// 结果: 5.546323

accDiv 两个浮点数相除

import { accDiv } from '@tntd/utils'
accDiv(5.31, 3.2);
// 结果: 1.659375 

accMul 两个浮点数相乘

import { accMul } from '@tntd/utils'
accMul(5.32, 3.233);
// 结果: 17.19956

accSub 两个浮点数相减

import { accSub } from '@tntd/utils'
accSub(5.3122, 3.234123);
// 结果: 2.078077  

random

randomColor 随机颜色

import { randomColor } from '@tntd/utils'
randomColor()    // #a0a362

randomNum 生成指定范围min, max的随机数

import { randomNum } from '@tntd/utils'
randomNum([2,9]);    // 4

series

desensitizedUtils 字段脱敏

import { desensitizedUtils } from '@tntd/utils'
desensitizedUtils.common('浙江省杭州市余杭区文一西路',3,-3)      // '浙江省*******一西路'
desensitizedUtils.email('hello@qq.com')                     // 'he***@qq.com'
desensitizedUtils.bankCard('6212268202014638888')           // '6212 **** **** 8888'
desensitizedUtils.phone('13888888888')                      // '138****8888'
desensitizedUtils.tel('0517-6756890')                       // '0***-675****'
desensitizedUtils.idNo('530381199908133239')                // '530381*********239'
desensitizedUtils.address('浙江省杭州市余杭区文一西路')         // '浙江省杭州市余杭区****'
desensitizedUtils.name('张三')                              // '张*'

regexpUtils 正则表达式

import { regexpUtils } from '@tntd/utils'
regexpUtils.isEmail('hello@qq.com')      // true

// isColor 判断是否为16进制颜色,rgb 或 rgba
// isEmail 判断是否为邮箱地址
// isIdCard 判断是否为身份证号,身份证号, 支持1/2代(15位/18位数字)
// isPhoneNumber 判断是否为手机号
// isTelNumber 判断是否为座机号 如: 0341-86091234
// isUrl 判断是否为URL地址
// isDomain 判断是否为 域名(非网址, 不包含协议)
// isIPv4 判断是否为 ip v4 地址
// isIPv6 判断是否为 ip v6 地址
// isBankNumber 判断是否为 银行卡号,10到30位, 覆盖对公/私账户
// isCnName 判断是否为 中文姓名
// isEnName 判断是否为 英文姓名
// isCarNumber 判断是否为 车牌号(新能源+非新能源)
// isPassportNumber 判断是否为 护照(包含香港、澳门)
// isPostNumber 判断是否为 邮政编码(中国)

typeUtils 类型判断工具箱

import { typeUtils } from '@tntd/utils'
typeUtils.isString('hello')      // true

// getType 获取变量准确类型
// isEmpty 判断元素是否为空
// isString 判断是否字符串
// isNumber 判断是否数字
// isBoolean 是否boolean
// isFunction 判断是否函数
// isNull 判断是否为null
// isUndefined 判断是否undefined
// isObject 判断是否对象
// isArray 判断是否数组
// isDate 判断是否时间
// isRegExp 判断是否正则
// isError 判断是否错误对象
// isSymbol 判断是否Symbol函数
// isPromise 判断是否Promise对象
// isSet 判断是否Set对象
// isFalse 判断是否是false
// isTrue 判断是否为true
// isPC 判断是否为 PC 端
// isMobile 判断是否为 mobile 端
// isDarkMode 判断浏览器是否是dark模式
// isIOS 判断是否IOS
// isAndroid 判断是否安卓

storage

safeStorage 设置localStorage

import { safeStorage } from '@tntd/utils'
// 可以直接填写object或者array,而不需要提前JSON.stringify
// 示例 
safeStorage.setItem("allMap",{     
    name:1,     
    type:2
});

// 安全取:safeStorage.getItem("名称","默认参数") 若取不出数据,则返回默认参数
// 示例
safeStorage.getItem("allMap",{     
    name:1,     
    type:1
});

// 删除  
safeStorage.removeItem("allMap");
0.1.21

8 months ago

0.1.20

8 months ago

0.1.19

8 months ago

0.1.18

8 months ago

0.1.17

8 months ago

0.1.16

8 months ago

0.1.15

8 months ago

0.1.14

8 months ago

0.1.13

8 months ago

0.1.12

8 months ago

0.1.11

8 months ago

0.1.10

8 months ago

0.1.9

8 months ago

0.1.8

8 months ago

0.1.7

8 months ago

0.1.6

8 months ago

0.1.5

8 months ago

0.1.4

8 months ago

0.1.3

8 months ago

0.1.2

8 months ago

0.1.1

8 months ago

0.1.0

8 months ago

0.0.8

8 months ago

0.0.7

8 months ago

0.0.6

8 months ago

0.0.5

8 months ago

0.0.4

8 months ago

0.0.3

8 months ago

0.0.2

8 months ago

0.0.1

8 months ago