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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@yolanda-qn/unit-transform

v1.2.2

Published

单位转换

Downloads

10

Readme

单位转换

安装

yarn add @yolanda-qn/unit-transform

使用

在模块中

import { kg2lb, Big, transform, UnitEnum } from '@yolanda-qn/unit-transform';

// 转为lb类型数据
const lb = kg2lb(64.56);

// 继续使用big.js库来进行精确计算
Big(lb).mul(14);

// 将数据展示到界面上
transform({
  value: 64.56,
  from: UnitEnum.KG,
  to: UnitEnum.STLB,
  trimTailZeros: true,
  fmt: '{0}st:{1}lb',
});
// 结果: { raw: [10, 2.4, false], text: "10st:2.4lb" }

在浏览器中

<script src="dist/browser/index.js"></script>
<script>
  const { version } = window.QN_globalUnitTransform;
  console.log(version);
</script>

Demo

在项目根目录下运行

npx anywhere -p 9099

在浏览器中查看index.html

self2self

自己转自己 since 1.0.0

import { self2self } from '@yolanda-qn/unit-transform';
// 或者
// import self2self from '@yolanda-qn/unit-transform/transformers/self2self';

const res = self2self('200.6');
console.log(res);
// 200.6
console.log(typeof res);
// number

单位(克)转其它单位

一般用于厨房秤

g2floz

since 1.0.0

import { g2floz } from '@yolanda-qn/unit-transform';
// 或者
// import g2floz from '@yolanda-qn/unit-transform/transformers/g2floz';

const res = g2floz(200.6);
console.log(res);
// 7.075162
console.log(typeof res);
// number

g2lboz

since 1.0.0

import { g2lboz } from '@yolanda-qn/unit-transform';
// 或者
// import g2lboz from '@yolanda-qn/unit-transform/transformers/g2lboz';

const res = g2lboz(200.6);
console.log(res);
// [0, 7.075162, false]
// 第一位表示 lb 单位。肯定是整数。
// 第二位表示 oz 单位
// 第三位表示是否是负数
// 一般如下方式来展示结果。这里的示例没考虑保留小数位数
const [lb, oz, isNegative] = res;
console.log(`${isNegative ? '-' : ''}${lb}:${oz}`);
// 0:7.075162

g2milkml

克转牛奶单位ml since 1.0.0

import { g2milkml } from '@yolanda-qn/unit-transform';
// 或者
// import g2milkml from '@yolanda-qn/unit-transform/transformers/g2milkml';

const res = g2milkml(200.6);
console.log(res);
// 194.75728155339806
console.log(typeof res);
// number

g2ml

克转ml,返回自身 since 1.0.0

import { g2ml } from '@yolanda-qn/unit-transform';
// 或者
// import g2ml from '@yolanda-qn/unit-transform/transformers/g2ml';

const res = g2ml(200.6);
console.log(res);
// 200.6
console.log(typeof res);
// number

单位(千克)转其它单位

一般用于体脂秤设备

kg2jin

since 1.0.0 千克转斤

import { kg2jin } from '@yolanda-qn/unit-transform';
// 或者
// import kg2jin from '@yolanda-qn/unit-transform/transformers/kg2jin';

const res = kg2jin(200.6);
console.log(res);
// 401.2
console.log(typeof res);
// number

kg2lb

since 1.0.0

import { kg2lb } from '@yolanda-qn/unit-transform';
// 或者
// import kg2lb from '@yolanda-qn/unit-transform/transformers/kg2lb';

const res = kg2lb(200.6);
console.log(res);
// 442.2
console.log(typeof res);
// number

kg2st

since 1.0.0

import { kg2st } from '@yolanda-qn/unit-transform';
// 或者
// import kg2st from '@yolanda-qn/unit-transform/transformers/kg2st';

const res = kg2st(200.6);
console.log(res);
// 31.585714285714285
console.log(typeof res);
// number

kg2stlb

since 1.0.0

import { kg2stlb } from '@yolanda-qn/unit-transform';
// 或者
// import kg2stlb from '@yolanda-qn/unit-transform/transformers/kg2stlb';

const res = kg2stlb(200.6);
console.log(res);
// [31, 8.2, false]
// 第一位表示 st 单位。肯定是整数。
// 第二位表示 lb 单位
// 第三位表示是否是负数
// 一般如下方式来展示结果。这里的示例没考虑保留小数位数
const [st, lb, isNegative] = res;
console.log(`${isNegative ? '-' : ''}${st}:${lb}`);
// 31:8.2

单位(lb)转其它单位

一般用于体脂秤设备

lb2jin

since 1.0.0

import { lb2jin } from '@yolanda-qn/unit-transform';
// 或者
// import lb2jin from '@yolanda-qn/unit-transform/transformers/lb2jin';

const res = lb2jin(200.6);
console.log(res);
// 181.9831261906922
console.log(typeof res);
// number

lb2kg

since 1.0.0

import { lb2kg } from '@yolanda-qn/unit-transform';
// 或者
// import lb2kg from '@yolanda-qn/unit-transform/transformers/lb2kg';

const res = lb2kg(200.6);
console.log(res);
// 90.9915630953461
console.log(typeof res);
// number

lb2st

since 1.0.0

import { lb2st } from '@yolanda-qn/unit-transform';
// 或者
// import lb2st from '@yolanda-qn/unit-transform/transformers/lb2st';

const res = lb2st(200.6);
console.log(res);
// 14.32857142857143
console.log(typeof res);
// number

lb2stlb

since 1.0.0

import { lb2stlb } from '@yolanda-qn/unit-transform';
// 或者
// import lb2stlb from '@yolanda-qn/unit-transform/transformers/lb2stlb';

const res = lb2stlb(200.6);
console.log(res);
// [14, 4.6, false]
// 第一位表示 st 单位。肯定是整数。
// 第二位表示 lb 单位
// 第三位表示是否是负数
// 一般如下方式来展示结果。这里的示例没考虑保留小数位数
const [st, lb, isNegative] = res;
console.log(`${isNegative ? '-' : ''}${st}:${lb}`);
// 14:4.6
/**
 * 这里为什么需要再给出一个 isNegative 字段呢
 * 这是因为假如是 -0st:1.9lb 这种情况,对于前面的st的值是0,是没办法把 -0 给出去的
 */

单位(厘米)转其它单位

一般用于身高和维度尺设备

cm2inch

厘米转英寸 since 1.1.0

import { cm2inch } from '@yolanda-qn/unit-transform';
// 或者
// import cm2inch from '@yolanda-qn/unit-transform/transformers/cm2inch';

const res = cm2inch(170.6);
console.log(res);
// 67.23947658836512
console.log(typeof res);
// number

cm2ft

厘米转英尺和英寸,一般展示为5'foot6"inch since 1.1.0

import { cm2ft } from '@yolanda-qn/unit-transform';
// 或者
// import cm2ft from '@yolanda-qn/unit-transform/transformers/cm2ft';

const res = cm2ft(170.6);
console.log(res);
// [5,7.239476588365127,false]
// 第一位表示 foot 单位。肯定是整数。
// 第二位表示 inch 单位
// 第三位表示是否是负数
// 一般如下方式来展示结果。这里的示例没考虑保留小数位数
const [foot, inch, isNegative] = res;
console.log(`${isNegative ? '-' : ''}${st}'${lb}"`);
// 5'7.239476588365127"
/**
 * 这里为什么需要再给出一个 isNegative 字段呢
 * 这是因为假如是 -0'foot1.9"inch 这种情况,对于前面的foot的值是0,是没办法把 -0 给出去的
 */

单位(英寸)转其它单位

一般用于身高和维度尺设备

inch2cm

英寸转厘米 since 1.1.0

import { inch2cm } from '@yolanda-qn/unit-transform';
// 或者
// import inch2cm from '@yolanda-qn/unit-transform/transformers/inch2cm';

const res = inch2cm(170.6);
console.log(res);
// 432.84632
console.log(typeof res);
// number

单位枚举值

since 1.0.0

export enum UnitEnum {
  KG = 'kg',
  LB = 'lb',
  JIN = 'jin',
  ST = 'st',
  // NOTE 这个单位在指标库里设置是 st_lb
  STLB = 'st:lb',
  // 厨房秤单位
  G = 'g',
  // 厨房秤单位。基本等同于g
  ML = 'ml',
  // 厨房秤单位
  LBOZ = 'lb:oz',
  /**
   * 厨房秤单位
   * @deprecated 请使用FLOZ
   */
  OZ = 'oz',
  // 厨房秤单位。等同于OZ
  FLOZ = 'fl.oz',
  // 厨房秤单位
  MILKML = 'milkml',
  /**
   * 厘米
   * @since 1.1.0
   */
  CM = 'cm',
  /**
   * 英寸
   * @since 1.1.0
   */
  INCH = 'inch',
  /**
   * 英尺。一般展示为5'foot6"inch
   * @since 1.1.0
   */
  FT = 'ft',
}
import { UnitEnum } from '@yolanda-qn/unit-transform';

转换工具函数

transform

since 1.0.0

  • 参数:

    • type: object
    • required: true
    • description: |名称|类型|是否必需|默认值|备注| |:--:|:--:|:--:|:--:|:--:| |value|string,number|是||要转换的值| |from|UnitEnum|是||原始单位| |to|UnitEnum|是||目标单位| |fmt|string|否||格式化字符串。例如: {0}st:{1}lb,最后展示文本类似为 1st:1.3lb| |fromFixedValue|number | (() => number | undefined)|否||原始单位保留小数位。| |toFixedValue|number | ((v: number | undefined) => number | undefined)|否||目标单位保留小数位。某些单位会根据原始单位的保留位数来决定目标原始单位的位数,这时候请传入一个函数,并指定fromFixedValue的值。例如: g 转为 lb:oz, g保留一位小数,计算后的lb:oz为两位| |trimTailZeros|boolean|否|true|是否去除小数部分尾部的0。例如:0.1300 => 0.13; 1.00 => 1; 0.00 => 0|
  • 参数:

    • type: (res: { raw: number; text: string; }) => any
    • required: false
    • description: 转换成功的回调
  • 参数:

    • type: (err: Error) => any
    • required: false
    • description: 执行失败的回调
  • 返回值:

    • type: { raw: number; text: string; }

完整测试用例如下

import { describe, expect, test, jest } from '@jest/globals';
import transform from '../src/transform';
import { UnitEnum } from '../src/unit.enum';

describe('transform', () => {
  test('transform g to g', () => {
    expect(transform({ value: 200, from: UnitEnum.G, to: UnitEnum.G })).toEqual({ raw: 200, text: '200' });
  });

  test('transform g to ml', () => {
    expect(transform({ value: 200, from: UnitEnum.G, to: UnitEnum.ML })).toEqual({ raw: 200, text: '200' });
  });

  test('transform g to milkml', () => {
    expect(transform({ value: 200, from: UnitEnum.G, to: UnitEnum.MILKML })).toEqual({ raw: 194.1747572815534, text: '194.2' });
  });

  test('transform g to floz', () => {
    expect(transform({ value: 200, from: UnitEnum.G, to: UnitEnum.FLOZ })).toEqual({ raw: 7.0548, text: '7.05' });
  });

  test('transform g to lboz', () => {
    expect(transform({ value: 601.33, from: UnitEnum.G, to: UnitEnum.LBOZ })).toEqual({ raw: [1, 5.21131442, false], text: '1:5.21' });
  });

  test('transform kg to kg', () => {
    expect(transform({ value: 54.123, from: UnitEnum.KG, to: UnitEnum.KG })).toEqual({ raw: 54.123, text: '54.12' });
  });

  test('transform kg to jin', () => {
    expect(transform({ value: 54.123, from: UnitEnum.KG, to: UnitEnum.JIN })).toEqual({ raw: 108.246, text: '108.25' });
  });

  test('transform kg to lb', () => {
    expect(transform({ value: 54.123, from: UnitEnum.KG, to: UnitEnum.LB })).toEqual({ raw: 119.4, text: '119.4' });
  });

  test('transform kg to st', () => {
    expect(transform({ value: 54.123, from: UnitEnum.KG, to: UnitEnum.ST })).toEqual({ raw: 8.528571428571428, text: '8.53' });
  });

  test('transform kg to stlb', () => {
    expect(transform({ value: 54.123, from: UnitEnum.KG, to: UnitEnum.STLB })).toEqual({ raw: [8, 7.4, false], text: '8:7.4' });
  });

  test('transform lb to lb', () => {
    expect(transform({ value: 54.123, from: UnitEnum.LB, to: UnitEnum.LB })).toEqual({ raw: 54.123, text: '54.1' });
  });

  test('transform lb to kg', () => {
    expect(transform({ value: 54.123, from: UnitEnum.LB, to: UnitEnum.KG })).toEqual({ raw: 24.550031751791707, text: '24.55' });
  });

  test('transform lb to jin', () => {
    expect(transform({ value: 54.123, from: UnitEnum.LB, to: UnitEnum.JIN })).toEqual({ raw: 49.100063503583414, text: '49.1' });
  });

  test('transform lb to st', () => {
    expect(transform({ value: 54.123, from: UnitEnum.LB, to: UnitEnum.ST })).toEqual({ raw: 3.8659285714285714, text: '3.87' });
  });

  test('transform lb to stlb', () => {
    expect(transform({ value: 54.123, from: UnitEnum.LB, to: UnitEnum.STLB })).toEqual({ raw: [3, 12.123, false], text: '3:12.1' });
  });

  test('transform any self to self', () => {
    expect(transform({ value: 54.123, from: 'not_exist', to: 'not_exist' })).toEqual({ raw: 54.123, text: '54.123' });
    expect(transform({ value: 54.123, from: 'not_exist', to: 'not_exist', toFixedValue: 2, fmt: '{0}千克' })).toEqual({ raw: 54.123, text: '54.12千克' });
    // successCallback should not be called
    const successCallback = jest.fn();
    const ret = transform({ value: 64.1023, from: 'not_exist', to: 'not_exist', toFixedValue: 2}, successCallback);
    expect(ret).toEqual({ raw: 64.1023, text: '64.1' });
    expect(successCallback).toBeCalledWith({ raw: 64.1023, text: '64.1' });
  });

  test('input string numeric value', () => {
    expect(transform({ value: '54.123', from: UnitEnum.KG, to: UnitEnum.LB })).toEqual({ raw: 119.4, text: '119.4' });
  });

  test('input negative value', () => {
    expect(transform({ value: '-54.123', from: UnitEnum.KG, to: UnitEnum.LB })).toEqual({ raw: -119.2, text: '-119.2' });
  });

  test('input negative value', () => {
    expect(transform({ value: -54.123, from: UnitEnum.KG, to: UnitEnum.STLB })).toEqual({ raw: [8, 7.2, true], text: '-8:7.2' });
  });

  test('input invalid arg:value (empty characters)', () => {
    // errorCatcher should be called.
    const errorCatcher = jest.fn();
    // successCallback should not be called
    const successCallback = jest.fn();
    const ret = transform({ value: '', from: UnitEnum.KG, to: UnitEnum.LB }, successCallback, errorCatcher);
    expect(ret).toEqual({ raw: 0, text: '' });
    expect(successCallback).not.toBeCalled();
    expect(errorCatcher).toBeCalledTimes(1);
    expect(errorCatcher).toBeCalledWith(expect.any(Error));
  });

  test('input invalid arg:value aa', () => {
    // errorCatcher should be called.
    const errorCatcher = jest.fn();
    // successCallback should not be called
    const successCallback = jest.fn();
    const ret = transform({ value: 'aa', from: UnitEnum.KG, to: UnitEnum.LB }, successCallback, errorCatcher);
    expect(ret).toEqual({ raw: NaN, text: 'aa' });
    expect(successCallback).not.toBeCalled();
    expect(errorCatcher).toBeCalledTimes(1);
    expect(errorCatcher).toBeCalledWith(expect.any(Error));
  });

  test('input invalid arg:from st', () => {
    // errorCatcher should be called.
    const errorCatcher = jest.fn();
    // successCallback should not be called
    const successCallback = jest.fn();
    const ret = transform({ value: 34, from: UnitEnum.ST, to: UnitEnum.LB }, successCallback, errorCatcher);
    expect(ret).toEqual({ raw: 34, text: '34' });
    expect(successCallback).not.toBeCalled();
    expect(errorCatcher).toBeCalledTimes(1);
    expect(errorCatcher).toBeCalledWith(new Error('[transform -> arg:from] is not a supported unit type, got st.'));
  });

  test('input invalid arg:to lboz as arg:from is set to kg', () => {
    // errorCatcher should be called.
    const errorCatcher = jest.fn();
    // successCallback should not be called
    const successCallback = jest.fn();
    const ret = transform({ value: 34, from: UnitEnum.KG, to: UnitEnum.LBOZ }, successCallback, errorCatcher);
    expect(ret).toEqual({ raw: 34, text: '34' });
    expect(successCallback).not.toBeCalled();
    expect(errorCatcher).toBeCalledTimes(1);
    expect(errorCatcher).toBeCalledWith(new Error('[transform -> arg:to] has no implements that transfrom kg to lb:oz.'));
  });

  test('test success callback', () => {
    expect(transform({ value: -54.123, from: UnitEnum.KG, to: UnitEnum.STLB })).toEqual({ raw: [8, 7.2, true], text: '-8:7.2' });
    // successCallback should be called
    const successCallback = jest.fn();
    // errorCatcher should not be called.
    const errorCatcher = jest.fn();
    transform({ value: 34, from: UnitEnum.KG, to: UnitEnum.JIN }, successCallback, errorCatcher);
    expect(errorCatcher).not.toBeCalled();
    expect(successCallback).toBeCalledTimes(1);
    expect(successCallback).toBeCalledWith({
      raw: 68,
      text: '68',
    });
  });

  test('test arg:fmt invalid', () => {
    // errorCatcher should be called.
    const errorCatcher = jest.fn();
    // successCallback should not be called
    const successCallback = jest.fn();
    const ret = transform({ value: 34, from: UnitEnum.KG, to: UnitEnum.LBOZ, fmt: 123 as unknown as string }, successCallback, errorCatcher);
    expect(ret).toEqual({ raw: 34, text: '34' });
    expect(successCallback).not.toBeCalled();
    expect(errorCatcher).toBeCalledTimes(1);
    expect(errorCatcher).toBeCalledWith(expect.any(Error));
  });

  test('test arg:fmt {0}st:{1}lb', () => {
    expect(transform({ value: 64.15, from: UnitEnum.KG, to: UnitEnum.STLB, fmt: '{0}st:{1}lb' })).toEqual({
      raw: [10, 1.4, false],
      text: '10st:1.4lb',
    });
  });

  test('test arg:fmt {0}千克', () => {
    expect(transform({ value: 64.15, from: UnitEnum.KG, to: UnitEnum.KG, fmt: '{0}千克' })).toEqual({
      raw: 64.15,
      text: '64.15千克',
    });
  });

  test('test arg:toFixedValue 1', () => {
    expect(transform({ value: 64.15, from: UnitEnum.KG, to: UnitEnum.KG, toFixedValue: 1 })).toEqual({
      raw: 64.15,
      text: '64.2',
    });
  });

  test('test arg:toFixedValue base on arg:fromFixedValue', () => {
    const res = transform({
      value: 64.1534,
      from: UnitEnum.KG,
      to: UnitEnum.KG,
      toFixedValue: (fromFixedValue) => ((fromFixedValue as number) + 1),
      fromFixedValue: 2,
    });
    expect(res).toEqual({
      raw: 64.1534,
      text: '64.153',
    });
  });

  test('test arg:trimTailZeros default set', () => {
    const res1 = transform({
      value: 64.1034,
      from: UnitEnum.KG,
      to: UnitEnum.KG,
      toFixedValue: 2,
    });
    const res2 = transform({
      value: 64.1034,
      from: UnitEnum.KG,
      to: UnitEnum.KG,
      toFixedValue: 2,
      trimTailZeros: true,
    });

    expect(res1).toEqual({
      raw: 64.1034,
      text: '64.1',
    });
    expect(res1).toEqual(res2);
  });

  test('test arg:trimTailZeros set false', () => {
    const res = transform({
      value: 64.1034,
      from: UnitEnum.KG,
      to: UnitEnum.KG,
      toFixedValue: 2,
      trimTailZeros: false,
    });

    expect(res).toEqual({
      raw: 64.1034,
      text: '64.10',
    });
  });
});

辅助函数

format

格式化函数 since 1.0.0

  • 参数:
    • type: string
  • 参数:
    • type: Record<PropertyKey, any> | PropertyKey[]
  • 返回值:
    • type: string
import { format } from '@yolanda-qn/unit-transform';
describe('format', () => {
  test('object params', () => {
    expect(format('{dayZone}好,{userName}!您今天有 {toDealWithNum} 条待办事项需要处理。', { dayZone: '早上', userName: '张三', toDealWithNum: 2 })).toBe('早上好,张三!您今天有 2 条待办事项需要处理。');
  });

  test('array params', () => {
    expect(format('{0}好,{1}!您今天有 {2} 条待办事项需要处理。', ['早上', '张三', 2 ])).toBe('早上好,张三!您今天有 2 条待办事项需要处理。');
  });
});

assert

断言函数 since 1.0.0

import { assert } from '@yolanda-qn/unit-transform';

const {
  isNumeric,
  assertNumeric,
  assertString,
  isNumber,
  assertNumber,
  isInteger,
  assertInteger,
  isFunction,
} = assert;

// 是否是数字型数据
isNumeric(1) // true
isNumeric(null) // false
isNumeric(undefined) // false
isNumeric(NaN) // false
isNumeric([1]) // false
isNumeric('1.2') // true
isNumeric('string') // false

assertNumeric('d', 'kg2lb') // TypeError: [kg2lb] expected a number type param, but got d.

assertString(1) // TypeError: expected a string type param, but got 1.

// 是否是number类型
isNumber(1) // true
isNumber(null) // false
isNumber(undefined) // false
isNumber([1]) // false
// 排除 NaN 值
isNumber(NaN) // false
isNumber('1.2') // false
isNumber('string') // false

assertNumber('string'); // TypeError: expected a number type param, but got string.

// 是否是整型 number 类型数据
isInteger(1) // true
isInteger(1.2) // false
isInteger(null) // false
isInteger(undefined) // false
isInteger(NaN) // false
isInteger([1]) // false
isInteger('1.2') // false
isInteger('string') // false

assertInteger(1.2) // TypeError: expected a integer number param, but got 1.2.

generateDefaultTransformConfigMap

生成默认映射表数据 since 1.0.0

1.1.0 添加cminch的配置

import { generateDefaultTransformConfigMap, TransformConfigMap } from '@yolanda-qn/unit-transform';

// TransformConfigMap 的初始值就是使用 generateDefaultTransformConfigMap 生成的
deepEqual(TransformConfigMap, generateDefaultTransformConfigMap)

getTransformTargetConfigInfo

获取配置信息 since 1.0.0

  • 参数:
    • type: UnitEnum
    • description: 原始单位
  • 参数:
    • type: UnitEnum;
    • description: 目标单位
  • 返回值:
    • type: TypeTransformConfig
    • description:
      type TypeTransformConfig = {
        target: UnitEnum | string;
        transformer(v: string | number): number | [number, number, boolean];
        /**
         * 格式化显示
        */
        fmt?: string;
        /**
         * 原始单位的小数位。
        * 对于像 g 转 fl.oz 和 lb.oz 单位。
        * 例如:6.1g 应该是要转为 0:0.22 的,这里的目标单位比原始单位多了一位小数位。
        */
        fromFixedValue?: number | (() => number | undefined);
        /**
         * 目标单位的小数位
        */
        toFixedValue?: number | ((v: number | undefined) => number | undefined);
      };
import { getTransformTargetConfigInfo, UnitEnum } from '@yolanda-qn/unit-transform';

getTransformTargetConfigInfo(UnitEnum.KG, UnitEnum.LB);

registerTransformConfig

注册一个新的转换配置。注意此操作是全局的,会影响 transform 函数的行为 since 1.0.0

  • 参数:

    • type: UnitEnum | string
    • required: true
    • description: 原始单位
  • 参数:

    • type: TypeTransformConfig
    • required: true
  • 参数:

    • type: boolean
    • description: 如果为true则替换已存在的单位。默认不替换
  • 返回值:

    • type: boolean
    • description: 是否注册成功。如果目标单位已存在,并且没有指定要替换已有值,则也返回false
import { registerTransformConfig } from '@yolanda-qn/unit-transform';

例如我们新加一个千克转克的转换配置

import { registerTransformConfig, UnitEnum, assert, transform } from '@yolanda-qn/unit-transform';

function kg2g(v: string | number) {
  assert.assertNumeric(v, 'kg2g');

  return v * 1000;
}

registerTransformConfig(UnitEnum.KG, {
  target: UnitEnum.G,
  transformer: kg2g,
  fmt: '{0}克',
  fromFixedValue: 2,
  toFixedValue: (fromFixedValue) => fromFixedValue,
});

transform({ value: 1.2, from: UnitEnum.KG, to: UnitEnum.G });
// 结果: { raw: 1200, text: '1200克' }

测试用例如下

  test('test registerTransformConfig fn', () => {
    registerTransformConfig(UnitEnum.KG, {
      target: UnitEnum.G,
      transformer: (v: number) => (v * 1000),
    });

    expect(TransformConfigMap.get(UnitEnum.KG)?.findIndex((item) => item.target === UnitEnum.G)).toBeGreaterThan(-1);

    registerTransformConfig(UnitEnum.KG, {
      target: UnitEnum.LB,
      transformer: Transformers.kg2lb,
      fmt: '{0}lb',
    });

    expect(TransformConfigMap.get(UnitEnum.KG)?.find((item) => item.target === UnitEnum.LB)?.fmt).toBe('');

    registerTransformConfig(UnitEnum.KG, {
      target: 'st-lb',
      transformer: Transformers.kg2stlb,
      fmt: '{0}:{1}',
    });

    expect(TransformConfigMap.get(UnitEnum.KG)?.find((item) => item.target === 'st-lb')?.fmt).toBe('{0}:{1}');

    // replace LB
    registerTransformConfig(UnitEnum.KG, {
      target: UnitEnum.LB,
      transformer: Transformers.kg2lb,
      fmt: '{0}lb',
    }, true);

    expect(TransformConfigMap.get(UnitEnum.KG)?.find((item) => item.target === UnitEnum.LB)).toEqual({
      target: UnitEnum.LB,
      transformer: Transformers.kg2lb,
      fmt: '{0}lb',
    });

    // register a new unit of from type
    registerTransformConfig('int', {
      target: 'double',
      transformer: (v: number) => v * 2,
    });

    expect(TransformConfigMap.has('int')).toBe(true);
    expect(transform({ value: 1, from: 'int', to: 'int' })).toEqual({ raw: 1, text: '1' });
    expect(transform({ value: 1, from: 'int', to: 'double' })).toEqual({ raw: 2, text: '2' });
    expect(transform({ value: 2, from: 'int', to: 'double' })).toEqual({ raw: 4, text: '4' });
  });

unregisterTransformConfig

移除转换配置 since 1.0.0

  • 参数:
    • type: UnitEnum | string
    • required: true
    • description: 原始单位
  • 参数:
    • type: UnitEnum | string
    • required: true
    • description: 目标单位
  • 返回值:
    • type: TypeTransformConfig | null
    • description: 被移除的转换配置
import { unregisterTransformConfig, UnitEnum } from '@yolanda-qn/unit-transform';

unregisterTransformConfig(UnitEnum.KG, UnitEnum.LB);

exports

export { default as Big } from 'big.js';

export { default as g2floz } from './transformers/g2floz';
export { default as g2lboz } from './transformers/g2lboz';
export { default as g2ml } from './transformers/g2ml';
export { default as g2milkml } from './transformers/g2milkml';
export { default as kg2jin } from './transformers/kg2jin';
export { default as kg2lb } from './transformers/kg2lb';
export { default as kg2st } from './transformers/kg2st';
export { default as kg2stlb } from './transformers/kg2stlb';
export { default as lb2kg } from './transformers/lb2kg';
export { default as lb2jin } from './transformers/lb2jin';
export { default as lb2st } from './transformers/lb2st';
export { default as lb2stlb } from './transformers/lb2stlb';
export { default as self2self } from './transformers/self2self';
/**
 * @since 1.1.0
 */
export { default as cm2inch } from './transformers/cm2inch';
/**
 * @since 1.1.0
 */
export { default as cm2ft } from './transformers/cm2ft';
/**
 * @since 1.1.0
 */
export { default as inch2cm } from './transformers/inch2cm';

export { default as transform } from './transform';
export { default as format } from './format';
export { UnitEnum } from './unit.enum';
export {
  TransformConfigMap, getTransformTargetConfigInfo, registerTransformConfig, unregisterTransformConfig,
} from './transform-map';
export type { TypeTransformConfig } from './transform-map';
export * as assert from './assert';

export { default as version } from './version';
export default {};

测试

yarn test

CHANGELOG