@klweb/utils v1.0.8
@klweb/utils
@klweb/utils 是一个模块化的 JavaScript 工具类库,提供一系列实用的函数和方法,以帮助开发者更高效、更便捷地处理常见的编程任务。
@klweb/utils 涵盖了一系列常用的工具函数,如:
字符串处理:用于操作和处理字符串。例如,你可以找到用于切割、连接、搜索和替换字符串的函数。
数组操作:对于处理数组,
@klweb/utils提供了一系列有用的函数,例如排序、过滤、映射等。这些函数可以帮助你轻松地处理数组数据。日期和时间处理:可以帮助你方便地处理日期和时间。
文件和流处理:对于需要处理文件或流的场景,这个库提供了一些函数和方法,例如读取文件、写入文件、解析流等。
错误处理:提供了一些工具用于错误处理,如捕获异常、生成错误等。
模块化的设计思路,更好的 Tree-Shaking 支持,每个工具函数都作为一个独立的模块提供。这种设计使得开发者可以根据自己的需要选择所需的模块,而不是被迫使用整个库。
📑 API 文档
🔸 debounce
防抖函数,在连续执行时只执行最后一次函数。
function debounce<T extends (...args: Array<any>) => any>(fn: T, interval?: number): T
在防抖函数中,当连续点击时,会取消之前的等待,重新开始计时。只有在等待时间内没有再次点击,才会执行原函数。
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| fn | (...args: Array<any>) => any | — | 接受一个任意数量、any 类型参数的函数 |
| interval | number | 500 | 间隔时间(以毫秒为单位) |
返回值
返回一个新函数
示例
import { debounce } from '@klweb/utils'
const func = debounce((arg1, arg2) => console.log(arg1, arg2), 500);
func('Hello', 'KLWeb-Utils!');
func('Hello', 'KLWeb-Utils!');
func('Hello', 'KLWeb-Utils!');
func('Hello', 'KLWeb-Utils!')
// 连续执行只会执行最后一次
// Expected output: Hello KLWeb-Utils!🔸 throttle
节流函数,限制函数的执行频率,每经过指定的时间间隔后才执行一次。
function throttle<T extends (...args: Array<any>) => any>(fn: T, interval?: number): T
节流函数是一种优化技术,用于限制函数的执行频率。它确保在指定的时间间隔内只执行一次原函数,从而减少频繁调用或连续执行的情况。
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| fn | (...args: Array<any>) => any | — | 接受一个任意数量、any 类型参数的函数 |
| interval | number | 1000 | 间隔时间(以毫秒为单位) |
返回值
返回一个新函数
示例
import { throttle } from '@klweb/utils'
const func = throttle((arg1, arg2) => console.log(arg1, arg2), 1500);
func('Hello', 'KLWeb-Utils!')🔸 getType
获取数据类型,一个能够校验字符串、数字、数组、对象等类型的函数。
function getType(value: any): Types
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| value | any | — | 接受一个任意类型的参数 |
返回值
返回字符串: string | number | boolean | object | array | function | undefined | null | bigint | symbol | date | regexp
示例
import { getType } from '@klweb/utils'
console.log(getType("Hello")); // 输出: string
console.log(getType(123)); // 输出: number
console.log(getType(BigInt(123))); // 输出: bigint
console.log(getType(Symbol('sym'))); // 输出: symbol
console.log(getType(true)); // 输出: boolean
console.log(getType(null)); // 输出: null
console.log(getType(undefined));// 输出: undefined
console.log(getType({})); // 输出: object
console.log(getType([])); // 输出: array
console.log(getType(function() {})); // 输出: function
console.log(getType(new Date())); // 输出: date
console.log(getType(/abc/)); // 输出: regexp🔸 dateFormatter
基于 moment.js 的日期时间格式器
function dateFormatter(date: DateTypes, pattern?: string, locale?: string): string
moment.js 是一个解析、校验、操作、显示日期和时间的
JavaScript工具库。
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| date | type DateTypes = Date / string / number | — | 待格式化的日期 |
| pattern | string | YYYY-MM-DD HH:mm:ss | 日期格式规则,更多规则 |
| locale | string | zh-cn | 区域语言 |
返回值
返回格式化后的日期
示例
import { dateFormatter } from '@klweb/utils'
const timestamp = 1692080368718;
console.log(dateFormatter(timestamp))
// Expected output: 2023-08-15 14:19:28
console.log(dateFormatter(timestamp, 'HH:mm:ss'))
// Expected output: 14:19:28🔸 getCurrentDateTime
获取当前日期时间
function getCurrentDateTime(pattern?: string, locale?: string): string
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| pattern | string | YYYY[年]MM[月]DD[日] dddd HH:mm:ss | 日期格式规则,更多规则 |
| locale | string | zh-cn | 区域语言 |
返回值
获取当前日期时间
示例
import { getCurrentDateTime } from '@klweb/utils'
console.log(getCurrentDateTime())
// Expected output: 2023年08月15日 星期二 15:11:50
console.log(getCurrentDateTime('HH:mm:ss'))
// Expected output: 15:13:33🔸 getUrlParamsRaw
获取浏览器地址栏 URL 所有参数值
function getUrlParamsRaw(): Record<string, any>
参数
无
返回值
返回一个对象,如果不存在则返回 {}。
示例
import { getUrlParamsRaw } from '@klweb/utils'
// https://www.klweb.com/index.html?a=1&b=2
const params = getUrlParamsRaw();
console.log(params)
// Expected output: { a: 1, b: 2}🔸 copyText
复制文本到剪贴板
function copyText(text: string, callback?: () => void): void
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| text | string | — | 要复制的文本 |
| callback | () => void | — | 回调函数 |
返回值
无返回值
示例
import { copyText } from '@klweb/utils'
const text = '这是一段测试文本';
copyText(text, () => {
console.log('Text successfully written to clipboard')
})🔸 htmlToEscape
HTML 转义符(HTML 标签转换为对应的 HTML 实体)。
function htmlToEscape(htmlText: string): string
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| htmlText | string | — | 待转义的 HTML 代码文本 |
返回值
返回处理后的 HTML 代码文本
示例
import { htmlToEscape } from '@klweb/utils'
const htmlText = `<p>这是一段测试代码</p>`;
console.log(htmlToEscape(htmlText))
// Expected output: "<p>这是一段测试代码</p>"🔸 escapeToHtml
HTML 反转义符(HTML 实体转换为对应的 HTML 标签)。
function escapeToHtml(htmlText: string): string
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| htmlText | string | — | 待转义的 HTML 代码文本 |
返回值
返回处理后的 HTML 代码文本
示例
import { escapeToHtml } from '@klweb/utils'
const htmlText = `<p>这是一段测试代码</p>`;
console.log(escapeToHtml(htmlText))
// Expected output: "<p>这是一段测试代码</p>"🔸 sumArray
数组求和
function sumArray(array: number[]): number
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| array | Array<number> | — | 要进行求和的数组数字 |
返回值
返回总和值
示例
import { sumArray } from '@klweb/utils'
const array = [2, 4, 5, 23, 100];
const total = sumArray(array);
console.log(total)
// Expected output: 134🔸 filterArray
根据给定的谓词函数过滤数组元素。filterArray,它是一个泛型函数,可以处理任意类型的数组。
function filterArray<T>(array: T[], predicate: (item: T) => boolean): T[]
函数内部调用了数组的 filter 方法,将谓词函数作为参数传入,对数组进行过滤操作。
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| array | Array<T> | — | 要进行过滤的数组 |
| predicate | (item: T) => boolean | — | 用于判断数组元素是否符合条件的谓词函数。它接受一个类型为 T 的参数,返回一个布尔值,用于判断数组元素是否符合条件。 |
返回值
返回过滤后的数组
示例
import { filterArray } from '@klweb/utils'
const items = [1, 2, 3, 4, 5];
const evenNumbers = filterArray(items, item => item % 2 === 0);
console.log(evenNumbers)
// Expected output: [2, 4]🔸 mapArray
数组元素映射。mapArray,它是一个泛型函数,可以处理任意类型的数组。
function mapArray<T, U>(array: T[], mapper: (item: T) => U): U[]
函数内部调用了数组的 map 方法,将映射函数 mapper 作为参数传入,对数组进行映射操作。
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| array | Array<T> | — | 要进行映射的数组 |
| mapper | (item: T) => U): U[] | — | 将数组元素映射为新值的函数。它将一个类型为 T 的元素映射为类型为 U 的新值,其中 T 和 U 是两个不同的类型。 |
返回值
返回映射后的新数组
示例
import { mapArray } from '@klweb/utils'
const names = ['Alice', 'Bob', 'Charlie'];
const capitalizedNames = mapArray(names, name => name.toUpperCase());
console.log(capitalizedNames)
// Expected output: ['ALICE', 'BOB', 'CHARLIE']🔸 findArray
查找数组中符合条件的元素。findArray,它是一个泛型函数,可以处理任意类型的数组。
function findArray<T>(array: T[], predicate: (item: T) => boolean): T | undefined
函数内部使用 for...of 循环遍历数组中的每个元素,并调用 predicate 函数进行条件判断。
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| array | Array<T> | — | 要进行查找的数组 |
| predicate | (item: T) => boolean | — | 用于判断元素是否符合条件的函数,接受一个类型为 T 的参数,返回一个布尔值。 |
返回值
返回值是一个类型为 T | undefined 的值,如果找到了符合条件的元素,则返回该元素,否则返回 undefined。
示例
import { findArray } from '@klweb/utils'
const list = [1, 2, 3, 4, 5];
const foundNumber = findArray(list, number => number === 3);
console.log(foundNumber)
// Expected output: 3🔸 uniqueArray
去除数组中的重复元素,并返回新的数组。
function uniqueArray<T>(array: T[]): T[]
函数内部使用 Set 数据结构来存储去重后的元素(因为 Set 会自动去除重复的键值),最后将 Set 对象转换为数组并返回。
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| array | Array<T> | — | 待处理的数组 |
返回值
返回处理后的新数组,不包含重复元素。
示例
import { uniqueArray } from '@klweb/utils'
const items = [1, 2, 2, 3, 4, 4, 5];
const uniqueItems = uniqueArray(items);
console.log(uniqueItems)
// Expected output: [1, 2, 3, 4, 5]🔸 uniqueArrayOfObjectByKey
去除数组对象中给定键名存在重复值的对象,并返回新的数组。
function uniqueArrayOfObjectByKey<T extends Record<string, any>>(array: T[], key: keyof T): T[]
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| array | Array<T> | — | 待处理的数组 |
| key | keyof T | — | 对象键名 |
返回值
返回处理后的新数组
示例
import { uniqueArrayOfObjectByKey } from '@klweb/utils'
const items = [
{ name: '张三', age: 24 },
{ name: '李四', age: 18 },
{ name: '张三', age: 24 },
{ name: '王五', age: 31 }
];
const uniqueItems = uniqueArrayOfObjectByKey(items, 'name');
console.log(uniqueItems)
// Expected output:
// [{ name: '张三', age: 24 }, { name: '李四', age: 18 }, { name: '王五', age: 31 }]🔸 sortArray
数组排序,支持中英文、数字排序。
function sortArray(array: Array<any>, order?: Order): Array<any>
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| array | Array<any> | — | 待排序的数组 |
| order | type Order = 'ascend' / 'descend' | ascend | 排序方式,升序:ascend,降序:descend |
返回值
返回处理后的新数组
示例
import { sortArray } from '@klweb/utils'
// 按字母 A-Z 排序
const arr1 = ['b', 'D', 'A', 'c'];
const sortArr1 = sortArray(arr1);
console.log(sortArr1)
// Expected output: ['A', 'b', 'c', 'D']
// 按数字排序
const arr2 = [3, 2, 1, 4];
const sortArr2 = sortArray(arr2);
console.log(sortArr2)
// Expected output: [1, 2, 3, 4]
// 按中文排序
const arr3 = ['白雪', '阿力', '陈九'];
const sortArr3 = sortArray(arr3);
console.log(sortArr3)
// Expected output: ['阿力', '白雪', '陈九']🔸 sortArrayOfObjectByKey
数组对象按给定键名的值排序,支持中英文、数字。
function sortArrayOfObjectByKey<T extends Record<string, any>>(array: Array<T>, key: keyof T, order?: Order): Array<T>
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| array | Array<T> | — | 待排序的数组 |
| key | keyof T | — | 对象键名 |
| order | type Order = 'ascend' / 'descend' | ascend | 排序方式,升序:ascend,降序:descend |
返回值
返回处理后的新数组
示例
import { sortArrayOfObjectByKey } from '@klweb/utils'
// 按字母 A-Z 排序
const arr1 = [
{ letter: 'b'},
{ letter: 'D'},
{ letter: 'A'},
{ letter: 'c'},
];
const sortArr1 = sortArrayOfObjectByKey(arr1, 'letter');
console.log(sortArr1)
// Expected output: [{ letter: 'A'}, { letter: 'b'}, { letter: 'C'}, { letter: 'D'}]
// 按数字排序
const arr2 = [
{ num: 3},
{ num: 2},
{ num: 1},
{ num: 4},
];
const sortArr2 = sortArrayOfObjectByKey(arr2, 'num');
console.log(sortArr2)
// Expected output: [{ num: 1 }, { num: 2}, { num: 3}, { num: 4}]
// 按中文排序
const arr3 = [
{ name: '白雪'},
{ name: '阿力'},
{ name: '陈九'},
];
const sortArr3 = sortArrayOfObjectByKey(arr3, 'name');
console.log(sortArr3)
// Expected output: [{ name: '阿力'}, { name: '白雪'}, { name: '陈九'}]🔸 deepCopy
深拷贝函数。
function deepCopy<T>(obj: T): T
该函数实现了深拷贝的功能,可以处理数组和对象的深度复制,避免了在复制过程中出现循环引用的问题。同时,使用类型断言来确保返回值的类型与输入的类型一致。
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| obj | <T> | — | 要复制的类型,接受一个泛型参数 T。如果传入的是数组,则使用 map() 方法递归复制每个元素;如果传入的是对象,则遍历每个属性并递归复制属性值;如果是其他类型,则直接返回该值。 |
返回值
返回新数组、对象或原始值
示例
import { deepCopy } from '@klweb/utils'
const obj = {
a: 1,
b: 2,
d: {
a: 5,
b: 0
}
};
const newObj = deepCopy(obj);
console.log(newObj)
// Expected output: { a: 1, b: 2, d: { a: 5, b: 0 } }🔸 deepMerge
深度合并对象
function deepMerge<T extends Record<string, any>>(...objects: Array<T>): T
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| objects | ...objects: Array<T> | — | 对象数组 |
返回值
返回新对象
示例
import { deepMerge } from '@klweb/utils'
const obj1 = {
a: 1,
b: 2,
d: {
a: 5,
b: 0
}
};
const obj2 = {
a: 4,
c: 3,
d: {
a: 2,
b: 1
}
};
const mergeObj = deepMerge(obj1, obj2);
console.log(mergeObj)
// Expected output: { a: 4, b: 2, c: 3, d: { a: 2, b: 1 } }🔸 sealMerge
密封一个对象,阻止其扩展并且原有属性不可配置,但属性值仍可写入。
function sealMerge<T extends Record<string, any>>(target: T, source: T): void
使用场景:
object1和object2两个对象进行合并,object1中的属性不可配置也不可扩展,只会合并object2中的与object1具有相同属性名的值,object2中的其它键值不会合并到object1中。
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| target | object | — | 要处理的目标对象 |
| source | object | — | 来源对象 |
返回值
无返回值
示例
import { sealMerge } from '@klweb/utils'
const obj1 = {
a: 1,
b: 2
};
const obj2 = {
a: 4,
b: 8,
c: 3,
d: 6
};
sealMerge(obj1, obj2);
console.log(obj1)
// Expected output: { a: 4, b: 8 }🔸 setCookie
设置 Cookie
function setCookie(key: string, value: string, expire?: number): void
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| key | string | — | 键名 |
| value | string | — | 键值 |
| expire | number | — | 过期天数,如:7 |
返回值
无返回值
示例
import { setCookie } from '@klweb/utils'
setCookie('sid', 'xxxxx', 7)🔸 getCookie
读取 Cookie
function getCookie(key: string): string
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| key | string | — | 键名 |
返回值
返回给定 key 的值
示例
import { getCookie } from '@klweb/utils'
const sid = getCookie('sid')
console.log(sid)
// Expected output: xxxxx🔸 removeCookie
删除 Cookie
function removeCookie(key: string): void
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| key | string | — | 键名 |
返回值
无返回值
示例
import { removeCookie } from '@klweb/utils'
removeCookie('sid')🔸 randomHexColor
随机生成 hex 十六进制颜色值
function randomHexColor(): string
参数
无
返回值
返回一个 hex 十六进制颜色值
示例
import { randomHexColor } from '@klweb/utils'
console.log(randomHexColor())
// Expected output: #ff03cc
console.log(randomHexColor())
// Expected output: #ba0efc🔸 hexToRgb
hex 颜色 转 rgb 颜色
function hexToRgb(hexColor: string): string
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| hexColor | string | — | 十六进制颜色字符串,支持 #RGB、#RRGGBB 格式,如:#fff、#ffffff |
返回值
返回 rgb 颜色值,如:rgb(255, 255, 255)
示例
import { hexToRgb } from '@klweb/utils'
const rgb = hexToRgb('#ffffff');
console.log(rgb)
// Expected output: rgb(255, 255, 255)🔸 rgbToHex
rgb 颜色 转 hex 颜色
function rgbToHex(rgbColor: string): string
参数
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| rgbColor | string | — | rgb 颜色字符串,如:rgb(255, 255, 255) |
返回值
返回一个 #RRGGBB 格式的 hex 十六进制颜色值
示例
import { rgbToHex } from '@klweb/utils'
const hex = rgbToHex(255, 255, 255);
console.log(hex)
// Expected output: #ffffff未完待续...