1.2.1 • Published 1 year ago
@kamuisdo/enum-helper v1.2.1
enum-helper
Install
npm i @kamuisdo/enum-helper --savepnpm add @kamuisdo/enum-helperIntroduce
- 封装枚举类型的对象,提供多种常用的方法,如根据枚举值获取整个枚举对象
- 兼容多种类型的属性值
How to use
import EnumHelper from '@kamuisdo/enum-helper'
// 实例化枚举对象
const myEnum = new EnumHelper([
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
])
myEnum.getById(1) // { id: 1, value: 'a' }
myEnum.getByValue('a') // { id: 1, value: 'a' }实例化
new EnumHelper接受一个item数组作为构造函数的参数,item对象中的id和value为必填项,可自定义其他属性
type plantType = number | string | boolean
type item = {
id: plantType
value: plantType
[key: string]: any
}id重复时会抛出错误
API
toObjectArray()- 返回整个item数组
getById(id)- 根据id返回item,如果id没有找到,返回undefined;如果id是null/NaN/undefined,返回undefined
getByValue(value)- 根据value返回item
getBy(key, keyValue)- 根据属性key获取item
const myEnum = new EnumHelper([
{
id: 1,
value: 'apple',
color: 'red',
share: () => {
return 'give you an apple'
},
}
])
myEnum.getByValue('color','red') // { id:1, value: 'apple', color ... }toArray(key)- 根据属性key获取对应值的数组
const myEnum = new EnumHelper([
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
])
myEnum.toArray('value') // ['a','b']toAntdSelectOptions()- 返回适用于AntdSelectOptions默认配置的数组
const myEnum = new EnumHelper([
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
])
myEnum.toAntdSelectOptions() // { value: 1, label: 'a' },{ value: 2, label: 'b' }