1.0.2 • Published 6 months ago

auto-unit v1.0.2

Weekly downloads
-
License
ISC
Repository
github
Last release
6 months ago

介绍

auto-unit 是一个精简的,自动选择合适的计量单位的库。

特性

  • 自动选择合适的计量单位
  • 支持自动切换科学计数法
  • 支持自定义进制位数
  • 支持自定义单位列表
  • 支持自定义小数位数
  • 支持自定义阈值

安装

npm install auto-unit

使用

const au = new AutoUnit([ 'b', 'kb', 'mb' ], {
  decimal: 1024,
})

console.log(au.toString(1024)) // 1kb

API

AutoUnit

export default class AutoUnit {
  constructor(units: string[], options?: AutoUnitOptions) {
  }
}

参数

  • units

    • 类型: string[]
    • 示例: ['b', 'kb', 'mb', 'gb', 'tb']

    计量单位列表

  • options

    配置项

getUnit

export default class AutoUnit {
  getUnit(num: number): { unit: string; num: number } {
  }
}

参数

  • num

    • 类型: number
    • 示例值: 1024 * 10

    数字,根据num自动选择合适的计量单位

返回值

返回值unit表示单位,num表示转换后的数字

toString

export default class AutoUnit {
  toString(num: number, decimalPlace?: number): string {
  }
}

参数

  • num

    • 类型: number
    • 示例值: 1024 * 10

    数字,根据num自动选择合适的计量单位

    • decimalPlace

    • 类型: number

    • 示例值: 2

    覆盖option.decimalPlace

    具体效果见DecimalPlace

Interface

AutoUnitOptions

export interface AutoUnitOptions {
  /** 进制位数 */
  decimal?: number
  /** 阈值 */
  threshold?: number
  /** 科学计数法 */
  exponential?: number
  /** 小数位数 */
  decimalPlace?: DecimalPlace
}

decimal

  • 类型: number
  • 示例值: 1000
  • 可选

进制位数

threshold

  • 类型: number
  • 示例值: 1024
  • 默认值: 1
  • 可选

阈值 表述超出进制位数的多少后开始升级单位

例如当设置threshold1024*2时,只有当num大于等于2048时才会使用kb为单位。 当然也可以设置为负数,例如-24,当num大于大于1000的时候就使用kb为单位。

exponential

  • 类型: number
  • 示例值: 1000
  • 可选

科学计数法

例如1024 * 1024 * 1000会被转换为1e+3md

科学计数法的生效与单位无关,只要最后的数字部分超过exponential就会生效。

decimalPlace

小数位数

DecimalPlace

export type DecimalPlace =
  | number
  | `-${ number }`
  | `${ number }-`
  | `${ number }-${ number }`
  | undefined

描述小数位数

当使用number时,固定小数位数,行为类似toFixed

当使用min-max时表示小数位保持在minmax之间,如果小数位不足min则填充0,如果超过max则截断

minmax各自可选,如果不指定,则表示不限制。但不能同时不指定,因为这样没有任何意义

扩展

你可以通过extend关键字来扩展AutoUnit。 具体的做法应该参考typescript的类的继承。

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

6 months ago

0.1.0

6 months ago