sheng-tool
    Preparing search index...

    sheng-tool

    sheng-tool

    一个小型 TypeScript 工具库,主要放那些项目里经常需要、但不值得为它们单独引入一整套大工具库的函数。

    pnpm add sheng-tool
    
    import { isEqualByPick, isSubset, toFiniteNumber } from 'sheng-tool';

    toFiniteNumber('1,234.5'); // 1234.5
    isSubset([{ id: 1 }], [{ id: 1 }, { id: 2 }]); // true
    isEqualByPick({ id: 1, name: 'a' }, { id: 1, name: 'b' }, ['id']); // true

    sheng-tool 只暴露根入口。array、object、number 等源码文件只是内部组织方式,不作为公开导入路径。

    浏览器相关工具也会继续从根入口导出,保持使用时的简洁性。包本身声明了 sideEffects: false,函数也不会在模块顶层访问 window。

    如果没有构建工具,也可以通过 unpkg 或 jsDelivr 引入 UMD 包:

    <script src="https://unpkg.com/sheng-tool/dist/index.umd.min.js"></script>
    <script>
    shengTool.toFiniteNumber('1,234.5'); // 1234.5
    </script>

    String.length 统计的是 UTF-16 code unit,遇到 emoji、国旗、肤色修饰、ZWJ 序列和组合音标时,常常和用户看到的字符数不一致。0.2.0 起可以用 Unicode grapheme cluster 语义处理用户输入文本:

    import {
    countUnicodeCharacters,
    sliceUnicodeCharacters,
    truncateUnicodeCharacters,
    truncateUtf16CodeUnits,
    } from 'sheng-tool';

    countUnicodeCharacters('A😀🇯🇵e\u0301'); // 4
    truncateUnicodeCharacters('A😀🇯🇵𠮷B', 3); // 'A😀🇯🇵'
    sliceUnicodeCharacters('A😀🇯🇵👍🏽B', 1, 4); // '😀🇯🇵👍🏽'
    truncateUtf16CodeUnits('A😀𠮷B', 3); // 'A😀'

    这些函数优先使用运行时的 Intl.Segmenter({ granularity: 'grapheme' }),没有 Intl.Segmenter 时会走内置 fallback。导入路径仍然只使用根入口,不新增 sheng-tool/string 这类 subpath。

    部分格式校验函数支持第二个参数:

    import { isBankCardCode, isEmail, isURL } from 'sheng-tool';

    isEmail('name+tag@example.com'); // true
    isURL('www.qq.com'); // true
    isURL('www.qq.com', 'strict'); // false
    isBankCardCode('6212263602033054274'); // true
    isBankCardCode('6212263602033054274', 'strict'); // false

    默认模式是 loose,适合前端输入层先做基础筛查;strict 会尽量走更明确的规范或校验码,例如 URL 必须是 HTTP(S) 完整地址,银行卡会执行 Luhn 校验。

    公开函数的 @example 会被 scripts/generate-example-tests.ts 转成 Vitest 用例。文档里的例子如果和真实行为不一致,pnpm test 会直接报错。

    生成器支持两种写法:

    • 表达式 // 期望值:自动转成 expect(表达式).toEqual(期望值)。
    • 表达式 // throws ErrorName:自动转成异常断言,适合说明不合理参数会报错。
    • 直接写包含 expect(...) 的代码块:用于少数确实需要放进文档的异常或复杂 setup。

    源码里的 @example 默认仍然写成读者能直接理解的普通例子;类型推导、循环引用这类测试细节优先放在 tests/ 里。

    每次生成还会写出 tests/generated/examples.report.json,记录生成了多少断言、哪些浏览器示例由手写测试覆盖,以及是否有无法解析的 @example。

    pnpm run generate:examples
    pnpm test
    pnpm run typecheck
    pnpm test
    pnpm run build
    pnpm run docs:build
    pnpm run pack:check

    pnpm run build 会清理产物、生成示例测试、跑类型检查、跑 Vitest,再输出 dist/index.mjs、dist/index.cjs、dist/index.d.ts、dist/index.d.cts、dist/index.umd.js 和 dist/index.umd.min.js。package.json 通过 exports.import 和 exports.require 明确区分 ESM/CJS 入口;类型内容只生成一份,再复制成 .d.cts 给 CJS 分支做模块格式标记。pnpm run pack:check 会在 build 后继续跑 package smoke test、publint 和 npm pack --dry-run。

    API 文档由 TypeDoc 生成,通过 GitHub Pages 发布到:

    https://dev-itsheng.github.io/sheng-tool/

    文档不会再随 npm 包一起发布,npm tarball 只包含运行时产物和类型声明。