wang-js-tools
v1.0.0
Published
通用工具函数库
Readme
wang-js-tools
通用 JavaScript 工具函数库,支持 ESM 和 CommonJS。
安装
npm install wang-js-tools使用
// ESM
import { hexToRGB, clamp, clampIndex, formatFileSize } from 'wang-js-tools';
// CommonJS
const { hexToRGB, clamp, clampIndex, formatFileSize } = require('wang-js-tools');工具列表
hexToRGB(hex)
将 hex 颜色转换为逗号分隔的 RGB 字符串,常用于设置 CSS 变量供 rgba() 使用。
| 参数 | 类型 | 说明 |
|------|------|------|
| hex | string | hex 颜色值,支持 #RGB 和 #RRGGBB 格式 |
| 返回值 | 类型 | 说明 |
|--------|------|------|
| RGB 字符串 | string | 逗号分隔的 RGB 值 |
hexToRGB('#1890ff'); // '24, 144, 255'
hexToRGB('#0f0'); // '0, 255, 0'
// 配合 CSS rgba() 使用
el.style.setProperty('--primary-color', hexToRGB('#1890ff'));
el.style.backgroundColor = 'rgba(var(--primary-color), 0.5)';clamp(value, min, max)
将数值限制在 [min, max] 范围内。
| 参数 | 类型 | 说明 |
|------|------|------|
| value | number | 原始值 |
| min | number | 最小值 |
| max | number | 最大值 |
| 返回值 | 类型 | 说明 |
|--------|------|------|
| 限制后的值 | number | 保证在 [min, max] 之间 |
clamp(10, 0, 5); // 5
clamp(-3, 0, 5); // 0
clamp(2, 0, 5); // 2clampIndex(index, length)
将数组下标限制在 [0, length-1] 范围内,防止越界访问。
| 参数 | 类型 | 说明 |
|------|------|------|
| index | number | 原始下标 |
| length | number | 数组长度 |
| 返回值 | 类型 | 说明 |
|--------|------|------|
| 安全下标 | number | 保证在 [0, length-1] 之间 |
const arr = ['a', 'b', 'c'];
clampIndex(5, arr.length); // 2
clampIndex(-1, arr.length); // 0
clampIndex(1, arr.length); // 1
clampIndex(0, 0); // 0(空数组安全返回 0)formatFileSize(bytes)
将字节数格式化为可读的文件大小字符串。
| 参数 | 类型 | 说明 |
|------|------|------|
| bytes | number | 字节数 |
| 返回值 | 类型 | 说明 |
|--------|------|------|
| 格式化字符串 | string | 如 '1.5 MB';null/NaN/<= 0 返回 '0 B' |
formatFileSize(0); // '0 B'
formatFileSize(1024); // '1.0 KB'
formatFileSize(1536); // '1.5 KB'
formatFileSize(1048576); // '1.0 MB'
formatFileSize(1610612736); // '1.5 GB'
formatFileSize(null); // ''
formatFileSize(NaN); // ''本地开发
# 安装依赖
npm install
# 开发模式(watch 构建)
npm run dev
# 构建发布产物
npm run build