npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

hzzt-utils

v1.0.5

Published

工具类

Readme

使用方法

npm install hzzt-utils

import {dataType} from 'hzzt-utils'

类型检查库

1. 基础类型检测

dataType(obj: unknown): DataType

返回值的具体类型字符串。

支持检测的类型:

type DataType =
    | 'boolean'    // 布尔值
    | 'number'     // 数字
    | 'string'     // 字符串
    | 'function'   // 函数
    | 'array'      // 数组
    | 'date'       // 日期对象
    | 'regExp'     // 正则表达式
    | 'undefined'  // undefined
    | 'null'       // null
    | 'object'     // 普通对象
    | 'blob'       // Blob对象
    | 'element'    // DOM元素
    | 'symbol';    // Symbol

示例:

dataType(42); // 'number'
dataType([]); // 'array'
dataType(document.body); // 'element'

2. 类型保护函数

基本类型检测

  • isString(value: unknown): value is string

  • isNumber(value: unknown): value is number

  • isBoolean(value: unknown): value is boolean

  • isArray<T = unknown>(value: unknown): value is T[]

  • isFunction(value: unknown): value is Function

  • isDate(value: unknown): value is Date

  • isRegExp(value: unknown): value is RegExp

  • isObject<T extends object = Record<string, unknown>>(value: unknown): value is T

  • isElement(value: unknown): value is Element

  • isBlob(value: unknown): value is Blob

  • isSymbol(value: unknown): value is symbol

  • isNull(value: unknown): value is null

  • isUndefined(value: unknown): value is undefined

  • isNil(value: unknown): value is null | undefined

示例:

if (isString(value)) {
// 在此块中,value被推断为string类型
    console.log(value.toUpperCase());
}

特殊检测

  • isPlainObject(value: any): value is object - 检测是否为纯对象(非数组、非null等)

  • isMergeableValue(value: any): boolean - 检测值是否可深度合并

  • isInstanceOf(value: unknown, constructor: Constructor): value is T - 检测是否为某类的实例

3. 实用工具函数

isSame<T>(a: T, b: T): boolean

深度比较两个值是否相同,支持对象和数组的深度比较。

特点:

  • 对基本类型使用严格相等(===)比较
  • 对复杂类型使用JSON序列化比较
  • 自动处理循环引用

示例:

isSame({a: 1}, {a: 1}); // true
isSame([1, 2], [1, 2]); // true

isEmpty(value: any): boolean

检测值是否为空值。

判断规则:

  • null/undefined → true

  • 空对象{} → true

  • 空数组[] → true

  • 空字符串'' → true

  • false → true

  • 其他 → false

HTML 处理工具库

1. HTML 检测与转换

isHtml(text: string = ''): boolean

检测字符串是否包含 HTML 标签。

检测规则:

  • 检查常见 HTML 结束标签 (</p>, </div>, </font>, </span>)
  • 检查常见单标签 (<br>, <sup>, <sub>)

示例:

isHtml('<p>Hello</p>'); // true
isHtml('Plain text');   // false

htmlToString(html: string | null | undefined): string

将 HTML 转换为纯文本,移除所有 HTML 标签并解码 HTML 实体。

处理逻辑:

  • 如果是空值返回空字符串
  • 如果不是 HTML 只解码实体
  • 如果是 HTML 先移除标签再解码实体

示例:

htmlToString('<p>Hello &amp; World</p>'); // "Hello & World"

2. 格式化转换

htmlToFormatString(html: string | null | undefined): string

将 HTML 转换为格式化的纯文本,保留部分换行结构。

转换规则:

  • <p><br></p> → 换行
  • <br> → 换行
  • <p></p> → 移除
  • &nbsp; → 空格
  • 保留 </p></div> 的换行效果

示例:

const html = '<p>Line1</p><p><br></p><p>Line2</p>';
htmlToFormatString(html);
// "Line1\n\nLine2"

3. 文本转 HTML

stringToHtml(str: string | null | undefined, tag: HtmlTag = 'p'): string

将纯文本转换为 HTML,支持两种格式:

参数:

  • tag: 'p' | 'br' - 指定转换格式:
  • 'p': 每行用 <p> 包裹
  • 'br': 换行转换为 <br/>

处理逻辑:

  • 编码特殊字符 (&, <, >, ")
  • 处理连续空格和开头空格
  • 根据指定标签格式转换

示例:

stringToHtml('Line1\nLine2', 'p');
// "<p>Line1</p><p>Line2</p>"

stringToHtml('Line1\nLine2', 'br');
// "Line1<br/>Line2"

文件处理工具库

1. 文件格式转换

convertBase64UrlToFile(urlData: string, extension?: string, type?: string): File

将 Base64 URL 字符串转换为 File 对象。

参数:

  • urlData: Base64 编码的字符串(可包含 data: 前缀)
  • extension: 文件扩展名(默认 'png')
  • type: MIME 类型(默认 'image/png')

示例:

const file = convertBase64UrlToFile('data:image/png;base64,iVBORw0KGgo...', 'png', 'image/png');

convertBlobToBase64(blob: Blob): Promise<Base64Result>

将 Blob 对象转换为 Base64 字符串。

返回:

interface Base64Result {
    base64: string; // Base64 数据部分
    type: string;   // MIME 类型部分
}

示例:

const {base64, type} = await convertBlobToBase64(blob);

2. 文件下载

downloadFile(data: string | Blob, fileName: string): Promise<void>

下载文件到本地。

支持:

  • 直接下载 URL 资源
  • 下载 Blob 对象内容
  • 自动释放 Blob URL 内存

示例:

// 下载 URL 文件
await downloadFile('https://example.com/file.pdf', 'document.pdf');


// 下载 Blob 内容
const blob = new Blob(['content'], {type: 'text/plain'});
await downloadFile(blob, 'note.txt');

3. PDF 打印

printPdf(data: Blob | string): Promise<void>

在浏览器中打印 PDF 文件。

特性:

  • 支持 Blob 对象或 URL 字符串
  • 使用隐藏 iframe 实现静默打印
  • 自动清理资源
  • 完善的错误处理

示例:

// 打印 URL PDF
await printPdf('https://example.com/doc.pdf');

// 打印 Blob PDF
const pdfBlob = await fetchPdfBlob();
await printPdf(pdfBlob);

对象操作工具库

1. 深度复制

deepCopy<T>(source: T, hash?: WeakMap<object, unknown>): T

创建对象的深度副本,支持处理循环引用和特殊对象类型。

支持的类型:

  • 基本类型(直接返回)
  • Date 和 RegExp 对象
  • Map 和 Set 集合
  • ArrayBuffer
  • 数组和普通对象
  • 包含 Symbol 属性的对象
  • 循环引用对象

示例:

const original = {a: 1, b: {c: 2}};
const copy = deepCopy(original);

// 处理循环引用
const obj: any = {self: null};
obj.self = obj;
const copied = deepCopy(obj); // 正确处理循环引用

2. 空值生成

getEmptyValueByType(value: any): any

根据输入值的类型返回对应类型的空值。

返回规则:

  • 数组 → 返回 []
  • 字符串 → 返回 ''
  • 对象 → 返回 {}
  • 其他 → 返回 undefined

示例:

getEmptyValueByType([1, 2, 3]); // []
getEmptyValueByType({a: 1});   // {}
getEmptyValueByType('text');     // ''

3. 深度合并

mergeObjects<T extends object | any[]>(a: T, b: Partial<T>): T

深度合并两个对象或数组,返回新对象(不修改原对象)。

合并规则:

  • 数组合并 → 连接两个数组
  • 对象合并 → 递归合并所有可枚举属性
  • 保留原型链
  • 跳过 null 和 undefined 值
  • 非对象/数组 → 直接覆盖

示例:

const obj1 = {a: 1, b: {c: 2}};
const obj2 = {b: {d: 3}, e: 4};
const merged = mergeObjects(obj1, obj2);
// { a: 1, b: { c: 2, d: 3 }, e: 4 }

几何计算工具库

1. 点坐标计算

getRectPoint(startPoint: Point, endPoint: Point): Point[]

根据矩形对角线的两个端点,计算矩形上的9个关键点坐标。

返回的点数组顺序:

  • 左上角

  • 上边中点

  • 右上角

  • 左边中点

  • 中心点

  • 右边中点

  • 左下角

  • 下边中点

  • 右下角

示例:

const points = getRectPoint(
    {x: 0, y: 0},   // 左上角
    {x: 100, y: 50} // 右下角
);
// 返回包含9个点的数组

getPointByAngle(cen: Point, first: Point, deg: number): Point

计算点绕中心点旋转指定角度后的新坐标。

参数:

  • cen: 旋转中心点
  • first: 要旋转的点
  • deg: 旋转角度(度)

示例:

const newPoint = getPointByAngle(
    {x: 50, y: 50},  // 中心点
    {x: 100, y: 50}, // 原始点
    45                 // 旋转45度
);

2. 几何判断

isPointInMatrix(p1: Point, p2: Point, p3: Point, p4: Point, p: Point): boolean

判断点是否在由四个点组成的矩形内。

参数顺序:

p1 —— p2
|    |
p3 —— p4

isPointInRegion(p: Point, region: Region): boolean

判断点是否在指定区域内。

Region接口:

interface Region {
    left: number;   // 左边界
    top: number;    // 上边界
    width: number;  // 宽度
    height: number; // 高度
}

isRangeIn(num: number, maxnum: number, minnum: number): boolean

判断数值是否在指定范围内。

示例:

isRangeIn(5, 10, 0); // true
isRangeIn(15, 10, 0); // false

3. 实用工具

getRandomId(): string

生成一个基于时间戳和随机数的唯一ID。

特点:

  • 包含16进制随机数
  • 附加当前时间戳
  • 极低的重叠概率

URL 处理工具库

1. 查询参数编码

encodeQueryData(data: Record<string, string | number | boolean>): string

将对象编码为 URL 查询字符串。

参数:

  • data: 键值对对象,值可以是字符串、数字或布尔值

返回值:

  • URL 编码后的查询字符串(不带前导的 ?)

示例:

const params = {
    name: "John Doe",
    age: 30,
    active: true
};

const queryString = encodeQueryData(params);
// 返回 "name=John%20Doe&age=30&active=true"

2. 查询参数获取

getQueryString(name: string): string | null

获取 URL 查询参数中指定名称的值。

参数:

  • name: 要获取的参数名

返回值:

  • 参数值(已解码)或 null(如果参数不存在)

示例:

// 对于 URL: http://example.com?name=John&age=30
const name = getQueryString("name"); // 返回 "John"
const missing = getQueryString("missing"); // 返回 null

getAllUrlRequest(_url?: string): Record<string, string> 获取 URL 中所有查询参数。

参数:

  • _url: 可选,指定要解析的 URL 字符串,默认为当前页面的查询部分

返回值:

包含所有查询参数的对象(键和值已解码)

示例:

// 对于 URL: http://example.com?name=John&age=30
const params = getAllUrlRequest();
// 返回 { name: "John", age: "30" }

事件处理工具库

  1. 事件监听(on/$on):注册事件监听器
  2. 单次监听(once/$once):只触发一次的事件监听器
  3. 事件触发(emit/$emit):触发指定事件
  4. 移除监听(off/$off):移除事件监听器
  5. 全部移除(removeAllListeners):清除所有事件监听

示例:

// 创建实例
const emitter = new EventEmitter();

// 添加点击事件监听
const clickHandler = (e: CustomEvent) => {
    console.log('点击位置:', e.detail.x, e.detail.y);
};
emitter.on('click', clickHandler);

// 添加一次性加载事件监听
emitter.once('load', () => {
    console.log('资源加载完成!');
});

// 触发事件
emitter.emit('click', {x: 100, y: 200});
emitter.emit('load');

// 移除特定事件监听
emitter.off('click', clickHandler);

// 清除所有监听
emitter.removeAllListeners();