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

@libeilong/func

v0.33.1

Published

一个在多项目中复用的通用工具函数集合,涵盖类型判断、对象处理、字符串与数字处理、随机工具、文件处理、时间与地理工具、错误与调试等常见场景。

Downloads

533

Readme

@libeilong/func

一个在多项目中复用的通用工具函数集合,涵盖类型判断、对象处理、字符串与数字处理、随机工具、文件处理、时间与地理工具、错误与调试等常见场景。

安装

pnpm add @libeilong/func
# 或
npm install @libeilong/func
# 或
yarn add @libeilong/func

本包声明了 dayjs 为 peerDependencies,部分与时间相关的工具可能依赖 dayjs。在使用这些工具时,请在你的项目中安装:

pnpm add dayjs

函数一览(按类别)

以下只列出主要工具函数名称,方便快速浏览。详细实现可以直接查看源码(大多为纯函数,易于理解)。

类型与环境判断

  • isNil / isNotNil:判断值是否为 nullundefined
  • isNumber:安全判断是否为数字
  • isClass:判断传入是否为类构造器
  • isServer:判断当前运行环境是否为服务端(SSR / Node)
  • isKeyOf:类型安全地判断 key 是否属于某个对象类型

对象与数组工具

  • objectKeys:带类型的 Object.keys
  • objectEntries:带类型的 Object.entries
  • objectPick:从对象中按键名挑选子集
  • insertBetweenElements:在数组元素之间插入分隔符
  • transDict:简单的字典转换/映射辅助

字符串与数字工具

  • convertToPascalCase:将字符串转换为 PascalCase
  • ensurePrefix:确保字符串带有指定前缀
  • omitText:按长度省略文本,追加省略号
  • toFixed:对数字做固定小数位格式化(带一些安全处理)
  • toFullNumberString:将数字转换为完整字符串(避免科学计数法)
  • formatSize:按 B / KB / MB / GB 等单位格式化字节大小

随机与 ID 工具

  • randomNumber:生成指定区间随机数
  • randomWeight:按权重随机选取元素
  • randomElement:从数组中随机选择一个元素
  • randomColor16:生成随机 16 进制颜色字符串
  • uniqueIdForSession:在当前会话内生成全局唯一 ID

时间与地理

  • getDateRangeStartingPoints:按天/周/月等范围生成起点时间(依赖 dayjs
  • measureLnglatDistance:测量两个经纬度之间的近似距离

文件与 Buffer 处理

  • file2Text:浏览器环境中将 File/Blob 转换为文本
  • file2Image:浏览器环境中将 File 转换为 HTMLImageElement
  • buffer2Text:Node/浏览器中将 ArrayBuffer / Buffer 转为字符串

错误与调试

  • error2string:将各种 Error/未知异常安全地转为字符串
  • extractErrorMessage:从异常对象中尽可能提取出人类可读的 message
  • printStackTrace:辅助打印堆栈信息
  • safeJsonParse:安全的 JSON 解析,避免直接抛错
  • noPromise:将返回 Promise 的函数转换为 Node 风格回调或更易用形式
  • sleep:延时等待(返回 Promise)

装饰器

  • executionTime:用于统计函数/方法执行时间的装饰器,方便简单埋点与性能调试

使用示例

基本导入方式

不建议一次性 import * as func,推荐按需导入,方便 Tree-Shaking:

import { isNil, objectPick, randomNumber } from '@libeilong/func'

if (!isNil(value)) {
  // ...
}

对象工具:objectPick

import { objectPick } from '@libeilong/func'

const user = { id: 1, name: 'Jack', age: 18, password: '***' }

const safeUser = objectPick(user, ['id', 'name'])
// => { id: 1, name: 'Jack' }

随机权重选择:randomWeight

import { randomWeight } from '@libeilong/func'

const list = [
  { value: 'A', weight: 1 },
  { value: 'B', weight: 3 },
  { value: 'C', weight: 6 },
]

const picked = randomWeight(list, (item) => item.weight)
// 返回其中一个元素,C 被选中的概率最高

文件转文本:file2Text

import { file2Text } from '@libeilong/func'

async function handleFile(file: File) {
  const text = await file2Text(file)
  console.log(text)
}

注意:file2Text / file2Image 仅适用于浏览器环境。

错误信息提取:extractErrorMessage

import { extractErrorMessage } from '@libeilong/func'

try {
  // ... 可能抛错的逻辑
} catch (err) {
  console.error('请求失败:', extractErrorMessage(err))
}

经纬度距离:measureLnglatDistance

import { measureLnglatDistance } from '@libeilong/func'

const distance = measureLnglatDistance(
  { lng: 116.397428, lat: 39.90923 },
  { lng: 121.473701, lat: 31.230416 },
)

console.log('北京到上海直线距离约(米):', distance)

执行时间装饰器:executionTime

import { executionTime } from '@libeilong/func'

class Demo {
  @executionTime('Demo.fetchData')
  async fetchData() {
    // 模拟耗时操作
    await new Promise((resolve) => setTimeout(resolve, 500))
  }
}

const demo = new Demo()
demo.fetchData()
// 控制台会打印类似:Execution time of Demo.fetchData: 500ms

使用建议

  • 尽量按需导入需要的工具函数,这样更利于打包体积优化。
  • 文件 / DOM 相关工具请仅在浏览器环境中使用;服务端(Node.js)中请留意环境判断(例如 isServer)。
  • 大部分函数都是无副作用的纯函数,可以放心在单元测试和业务代码中复用。

许可证

本项目基于 MIT 协议开源,详见本包内的 LICENSE 文件。