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

@lhy-meta-web/convert-units

v1.0.1

Published

公英制单位换算工具库,基于 anchor/ratio 锚点比率架构,内置常用度量并支持扩展

Readme

@lhy-meta-web/convert-units

公英制单位换算工具库。基于业界成熟的 anchor/ratio(锚点比率) 架构设计,内置常用度量类别,提供可扩展接口,运行期换算为 O(1)。

特性

  • 成熟架构:借鉴 convert-units 的锚点比率模型,换算路径固定,精度可控、无误差累积。
  • 内置常用度量:长度、质量、温度、体积、面积、速度,覆盖公制与英制。
  • 编译期类型安全from 只接受合法单位,to 只接受与源单位「同度量类别」的兼容单位,非法用法在编译期即报错。
  • 国际化(i18n):内置简体中文,支持按语言返回单位与度量类别的本地化名称,可增量注册任意语言。
  • 高性能:注册阶段将单位展开为扁平索引表,单次换算为 O(1) 查表 + 常数次算术。
  • 可扩展:支持动态注册自定义度量类别与单位。
  • 类型完备:全量 TypeScript 类型定义。
  • 测试完善:基于 Vitest,语句 / 分支 / 函数 / 行覆盖率 100%,并含类型层面(type-level)测试。

安装

pnpm add @lhy-meta-web/convert-units

快速开始

import convert from '@lhy-meta-web/convert-units'

// 公↔英
convert(1).from('lb').to('kg') // 0.45359237
convert(1).from('ft').to('m') // 0.3048

// 温度(仿射变换)
convert(100).from('C').to('F') // 212
convert(0).from('C').to('K') // 273.15

// 同制内换算
convert(1).from('km').to('m') // 1000

核心架构

每种「度量类别(Measure)」下的单位被划分到不同「单位制(System)」(如 metric / imperial):

  • 同一单位制内所有单位以「锚点单位(anchor)」为基准,通过 toAnchor 比率换算。
  • 不同单位制之间通过「锚点桥接(AnchorBridge)」转换,桥接可以是比率(ratio)或变换函数(transform,用于温度)。

换算路径:

源单位值 → 源单位制锚点值 → 目标单位制锚点值 → 目标单位值

API

链式换算

convert(value).from(fromAbbr).to(toAbbr) // 换算到指定单位
convert(value).from(fromAbbr).toAll() // 一次换算到同类别所有单位
convert(value).from(fromAbbr).toBest(options?) // 自动选择最易读单位

toBest 选项:

| 字段 | 说明 | 默认值 | | -------------- | ------------------------------------------ | ------ | | cutOffNumber | 结果绝对值不小于该值时才作为候选 | 1 | | system | 限定候选单位所属单位制(如仅 metric) | 全部 | | locale | 结果单位名称的语言,省略时用默认语言 | 默认 |

元信息

convert.possibilities('m') // 与 m 兼容的所有单位缩写
convert.possibilities() // 全部单位缩写
convert.measures() // 全部度量类别
convert.describe('m') // { abbr, measure, measureName, system, singular, plural }

类型安全

单位缩写在编译期即受约束,配合 IDE 可获得自动补全与错误提示:

convert(1).from('m').to('cm') // ✅ 合法
convert(1).from('m').to('km') // ✅ 合法(同为长度)

convert(1).from('xxx') // ❌ 编译报错:'xxx' 不是合法单位
convert(1).from('m').to('kg') // ❌ 编译报错:'kg'(质量)与 'm'(长度)不兼容

同时导出类型级工具,便于在业务代码中做类型推导:

import type {
  AllUnitAbbrs, // 全部合法单位缩写
  BuiltinMeasures, // 内置度量集合的精确类型
  CompatibleUnits, // 与某单位兼容的单位集合
  MeasureKeyOfUnit, // 某单位所属的度量类别
} from '@lhy-meta-web/convert-units'

type LengthUnits = CompatibleUnits<BuiltinMeasures, 'm'> // 'nm' | 'mm' | ... | 'ft' | ...
type MeasureOfKg = MeasureKeyOfUnit<BuiltinMeasures, 'kg'> // 'mass'

通过 createConverter 注册的自定义度量,同样会从字面量定义中推导出精确的单位类型。

国际化(i18n)

内置简体中文(zh-CN)。默认语言为 en(返回单位定义中的英文原始名称)。

import convert from '@lhy-meta-web/convert-units'

// 切换默认语言
convert.setLocale('zh-CN')
convert.describe('kg') // { ..., singular: '千克', measureName: '质量' }

// 单次指定语言,不改变默认语言
convert.describe('m', 'zh-CN') // { ..., singular: '米' }
convert(1200).from('m').toBest({ locale: 'zh-CN' }) // { ..., singular: '千米' }

// 注册(或增量合并)自定义语言
convert.registerLocale('ja', {
  units: { m: { singular: 'メートル', plural: 'メートル' } },
  measures: { length: '長さ' },
})
convert.describe('m', 'ja').singular // 'メートル'

未命中翻译时会自动回退到单位定义中的英文原始名称,保证永远有可用文案。

创建实例时也可直接配置语言:

import { createConverter } from '@lhy-meta-web/convert-units'

const converter = createConverter(undefined, { defaultLocale: 'zh-CN' })
converter.describe('kg').singular // '千克'

内置单位

| 度量类别 | 中文 | 公制 | 英/美制 | | ------------------ | -------- | ------------------------- | ------------------------ | | length | 长度 | nm, um, mm, cm, dm, m, km | in, ft, yd, mi | | mass | 质量 | mcg, mg, g, kg, mt | oz, lb, st, t | | temperature | 温度 | C, K | F, R | | volume | 体积 | ml, cl, dl, l, kl, m3 | fl-oz, cup, pnt, qt, gal | | area | 面积 | mm2, cm2, m2, ha, km2 | in2, ft2, yd2, ac, mi2 | | speed | 速度 | m/s, km/h | mph, ft/s, knot | | coolingCapacity | 制冷量 | kW | RT | | coolingEnergy | 累计冷量 | kWh | RTh | | pressure | 压力 | kPa | psi | | flow | 流量 | m3/h | USGPM | | efficiency | 能效系数 | COP | kW/RT |

暖通空调(HVAC)换算关系

| 名称 | 公制单位 | 英/美制单位 | 换算关系(保留 3 位小数) | | -------- | -------- | ----------- | ---------------------------- | | 制冷量 | kW | RT(冷吨) | 1 RT = 3.517 kW | | 累计冷量 | kWh | RTh | 1 RTh = 3.517 kWh | | 压力 | kPa | psi | 1 psi = 6.894 kPa | | 流量 | m³/h | USGPM | 1 USGPM = 0.227 m³/h | | 能效系数 | COP | kW/RT | kW/RT = 3.517 ÷ COP(倒数) |

能效系数是「倒数」关系(非比率、非仿射),库内通过双向 transform 函数桥接: kW/RT = 3.517 ÷ COPCOP = 3.517 ÷ (kW/RT)

扩展自定义度量

import { createConverter } from '@lhy-meta-web/convert-units'

const converter = createConverter()

// 注册一个全新的度量类别
converter.getRegistry().add('data', {
  systems: {
    binary: {
      b: { toAnchor: 1, name: { singular: 'Byte', plural: 'Bytes' } },
      kb: { toAnchor: 1024, name: { singular: 'Kilobyte', plural: 'Kilobytes' } },
    },
  },
  anchors: {},
})

converter.convert(1).from('kb').to('b') // 1024

// 向已有度量追加单位
converter.getRegistry().addUnit('length', 'metric', 'Mm', {
  toAnchor: 1e6,
  name: { singular: 'Megameter', plural: 'Megameters' },
})

错误处理

| 错误类型 | 触发场景 | | ------------------------ | ---------------------------- | | UnknownUnitError | 单位缩写未注册 | | IncompatibleUnitError | 源与目标属于不同度量类别 | | MissingBridgeError | 两单位制之间缺少桥接关系 | | ConvertError | 上述错误的基类 |

所有错误均继承自 ConvertError,可通过 instanceof 精确捕获。

脚本

pnpm build      # 构建库产物
pnpm typecheck  # 类型检查(tsc --noEmit)
pnpm test       # 运行测试(含类型层面测试)
pnpm coverage   # 运行测试并生成覆盖率报告

License

MIT