# dl-utils

> 便捷开发工具

Latest version **1.4.0** (published 2024-05-29) · ISC license · 0 weekly downloads

## Install

```sh
npm install dl-utils
pnpm add dl-utils
yarn add dl-utils
bun add dl-utils
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.4.0 |
| Published | 2024-05-29 |
| First published | 2020-10-26 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 48 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | taptop |
| Maintainers | smjb |
| Keywords | dl, dl-, util, util-, utils, dl-util, dl-utils |

## Links

- npm: https://www.npmjs.com/package/dl-utils
- npm.io page: https://npm.io/package/dl-utils

## Alternatives

- [localforage](https://npm.io/package/localforage.md) — 6.2M weekly downloads
- [localforage-observable](https://npm.io/package/localforage-observable.md) — 30.8K weekly downloads
- [@y/y](https://npm.io/package/@y/y.md) — 30.1K weekly downloads
- [@metaobjectsdev/render](https://npm.io/package/@metaobjectsdev/render.md) — 3.5K weekly downloads
- [@ledgerhq/coin-algorand](https://npm.io/package/@ledgerhq/coin-algorand.md) — 1.1K weekly downloads

## Recent versions

- 1.4.0 (latest) — 2024-05-29
- 2.0.0 — 2023-01-11
- 1.3.11 — 2022-12-09
- 1.3.9 — 2022-12-08
- 1.3.7 — 2022-10-10
- 1.3.6 — 2022-10-10
- 1.3.5 — 2022-10-10
- 1.3.4 — 2022-10-08
- 1.3.3 — 2022-09-30
- 1.3.2 — 2022-09-02
- 1.3.1 — 2022-09-02
- 1.2.9 — 2022-09-02
- 1.2.8 — 2022-09-02
- 1.2.7 — 2022-09-02
- 1.2.6 — 2022-08-25
- … 34 more at https://npm.io/package/dl-utils/versions

## README

# **安装**

```npm
npm install dl-utils
```

# 更新说明

**2023-11-08（ version 2.0.1）**

**1. 新增消息队列**

# **API 文档**

## PipelineClass【管道】

### regExp (正则库)

|    属性名     |                                      说明                                       |
| :-----------: | :-----------------------------------------------------------------------------: |
|    ACCOUNT    |                         常规账号类型，只支持数字，字母                          |
|   PASSWORD    | 常规密码类型，除了特殊字符和文字，其它都可以输入，可用字符（~!@#$%^\_.,?:/...） |
|     TEXT      |                           常规文本类型，除了特殊字符                            |
|     PHONE     |                          常规手机号类型，只能输入数字                           |
| IDENTITY_CARD |                     常规身份证类型，只能输入数字和字母（x）                     |

### pipeline (正则过滤数据)

```javascript
/**
 * 管道过滤数据
 * @param {string} source 需要过滤的数据
 * @param {string} regexp 正则匹配 | 字符匹配
 * @returns 过滤后的值
 */
const pipeline = ((source = ""), (regexp = ""));
```

**例如：**

```javascript
const { PipelineClass } from 'dl-utils';

// 过滤掉 'b'
PipelineClass.pipeline('abc','b') // 返回结果：'ac'

// 只能是数字
PipelineClass.pipeline('12bc12',/(^[0-9])/) // 返回结果：'bc'

// 搭配正则库校验
PipelineClass.pipeline('138x000x111x22',RegExpClass.regExp.PHONE) // 返回结果：'13800011122'
```

## MonitorClass【迷你监听器】

### on (订阅/监听)

```javascript
  /**
   * 订阅/监听
   * @param eventName
   * @param callback
   */
  on(eventName: string, callback?: Function)
```

### emit (发布/触发)

```javascript
  /**
   * 发布/触发
   * @param eventName
   * @param args
   */
  emit(eventName: string, ...args: any)
```

### once (订阅一次/监听一次)

```javascript
  /**
   * 订阅一次/监听一次
   * @param eventName
   * @param callback
   */
  once(eventName: string, callback?: Function)
```

### off (卸载/取消)

```java
  /**
   * 卸载/取消 某个回调的监听
   * @param eventName
   * @param callback
   */
  off(eventName: string, callback: Function)
```

**例子：**

```javascript
import { MonitorClass } from "dl-utils";

const a = new MonitorClass();

// 订阅参数
a.on("test", (value) => {
  console.log(`我是监听到的值${value}`);
});
// 发布参数
setTimeout(() => {
  a.emit("test", "更新参数啦");
}, 1000);
```

## DateFormatClass【时间日期转换工具】

### timestampToDateFormat **(时间戳转日期)**

**timestampToDateFormat（时间戳，格式）**

```javascript
 *  日期格式说明
 *  yyyy-MM-dd hh:mm:ss.S ==> 2020-07-02 08:09:04.423
 *  yyyy-MM-dd E HH:mm:ss ==> 2020-03-10 一 20:09:04
 *  yyyy-MM-dd EE hh:mm:ss ==> 2020-03-10 周一 08:09:04
 *  yyyy-MM-dd EEE hh:mm:ss ==> 2020-03-10 星期一 08:09:04
 *  yyyy-M-d h:m:s.S ==> 2020-7-2 8:9:4.18
```

```javascript
import { DateFormatClass } from "dl-utils";
let date = DateFormatClass.timestampToDateFormat(
  1604046014,
  "yyyy-MM-dd hh:mm:ss"
);
console.log(date); // console.log(2020-10-30 16:20:34)
```

### dateFormat **(日期格式转换)**

**dateFormat（日期，格式）**

```javascript
import { DateFormatClass } from "dl-utils";
let date = DateFormatClass.dateFormat(
  "2020/10/30 16:20:34",
  "yyyy-MM-dd hh:mm:ss"
);
console.log(date); // console.log(2020-10-30 16:20:34)
```

### timestampToDate **(时间戳转时间)**

**例示：**

```javascript
import { DateFormatClass } from "dl-utils";
let date = DateFormatClass.timestampToDate(
  "Thu Jan 12 2020 16:20:34 GMT+0800 (中国标准时间)"
);
console.log(date); // console.log(1604046014)
```

## OperationClass【操作工具】

### copy **(复制)**

```javascript
import { OperationClass } from "dl-utils";
OperationClass.copy("我是复制的内容");
```

## ToastClass 【提示工具】

### show **(消息提示)**

```javascript
import { ToastClass } from 'dl-utils';
ToastClass.show({
    msg:"我是显示的内容"，
    time:3000
})
```

## MappingClass【数据映射工具】

### mapToEnumByObject **(映射枚举数据 - 对象)**

```javascript
/**
 *
 * 枚举映射
 * @param {Array} source 修复数据
 * @param {Object} target 枚举数据
 * @param {String} field 修改的字段
 * @return 修改后的数据
 */
mapToEnumByObject(source, target, field);
```

```javascript
import { MappingClass } from "dl-utils";
let array = [
  { id: 0, name: "a", sex: 1 },
  { id: 1, name: "b", sex: 2 },
  { id: 2, name: "a", sex: 1 },
];

let data = MappingClass.mapToEnumByObject(
  array,
  { 1: "boy", 2: "gire" },
  "sex"
);

console.log(data);
// [{ id: 0, name: 'a', sex: 'boy' },{ id: 1, name: 'b', sex: 'gire' },{ id: 2, name: 'a', sex: 'boy' }]
```

### mapToEnumByList **(映射枚举数据 - 数组)**

```javascript
/**
 * 枚举映射
 * @param {Array} source 源数据
 * @param {Array} target 枚举数据
 * @return 修改后的数据
 */
mapToEnumByList(source, target);
```

```javascript
import { MappingClass } from "dl-utils";
let array = [
  { id: 0, name: "a", sex: 1 },
  { id: 1, name: "b", sex: 2 },
  { id: 2, name: "a", sex: 1 },
];
let enums = {
  sex: { 1: "boy", 2: "gire" },
  name: { a: "1001", b: "1002" },
};

let data = MappingClass.mapToEnumByList(array, enums);

console.log(data);
// [{ id: 0, name: '1001 sex: 'boy' },{ id: 1, name: '1002', sex: 'gire' },{ id: 2, name: '1001', sex: 'boy' }]
```

## FilterClass 【过滤工具】

### listInFieldsSetValue **(更新某个属性里的值 )**

**listInFieldsSetValue(Ar ray=源数据,Object=过滤数据 , 回调= (key,item,updateValue)=>{} )**

```javascript
import { FilterClass } from "dl-utils";
const source = [
  { id: 1, person_x: 3, person_y: 13 },
  { id: 2, person_x: 8, person_y: 24 },
];

// 普通使用
const target_1 = { person_x: "rem", person_y: "px" };

let list_1 = FilterClass.listInFieldsSetValue(source, target_1);
console.log(list_1);
// [{id:1,person_x:'3rem',person_y:'13px'},{id:2,person_x:'8rem',person_y:'24px'}];

// 自定义过滤方式
const target_2 = { person_x: "X轴", person_y: "Y轴" };

let list_2 = FilterClass.listInFieldsSetValue(
  source,
  target_2,
  (key, old, now) => {
    return now[key] + old[key];
  }
);
console.log(list_2); // [{id:1,person_x:X轴3,person_y:Y轴13},{id:2,person_x:X轴8,person_y:Y轴24}];
```

### replaceAttributNameByObject **(对象的属性名称修改)**

**objectFilterByAttribute(source[Object]=源数据 , target[Object]=过滤数据)**

```javascript
import { FilterClass } from "dl-utils";

let source = { id: 1, name: "小明", age: 18 };
let target = { id: "code", name: "userName" };

let data = FilterClass.replaceAttributName(source, target);
console.log(data);
// { code: 1, userName: '小明', age: 18 }
```

### replaceAttributNameByList **(对象数组的属性名称修改)**

**replaceAttributNameByList (source[Array]=源数据 , target[Object]=过滤数据)**

```javascript
import { FilterClass } from "dl-utils";

let source = [
  { id: 1, name: "小明" },
  { id: 2, name: "小红" },
];
let target = { type: "none" };

let data = FilterClass.replaceAttributNameByList(source, target);
console.log(data);
// [ { id: 1, name: '小明' }, { id: 2, name: '小红' } ]
```

### recursionBase **(无限级递归数据)**

**PS：根据 父级节点进行递归（全部数据都会加上 children 属性）**

**recursionBase(**

**source[Array]=源数据，**

**pid[Number]=父级 id,**

**parentIdName[String]=父级 id 的属性名,**

**idName[String]=自身 id 的属性名**

**)**

```javascript
import { FilterClass } from "dl-utils";

let source = [
  { id: 1, pid: 0, name: "test" },
  { id: 2, pid: 0, name: "test" },
  { id: 3, pid: 1, name: "test" },
];

let data = FilterClass.recursionBase(source, 0, "pid", "id");
console.log(data);
// [{id:1,pid:0,name:"test",children:[{id:3,pid:1,name:"test"}]},{id:2,pid:0,name:"test",children:[]}]
```

### recursionBaseSuper **(无限级递归数据)**

**PS：如果有数据会创建一个属性并且添加数据，如果没有则不添加该属性**

**recursionBaseSuper(**

**source[Array]=源数据，**

**id[String]=自身 id 的字段名,**

**pid[String]=关联父级 id 的字段名,**

**childrenName[String]=自定义子节点的属性名。 默认：children **

**)**

```javascript
import { FilterClass } from "dl-utils";

let source = [
  { id: 1, pid: 0, name: "test" },
  { id: 2, pid: 0, name: "test" },
  { id: 3, pid: 1, name: "test" },
];

let data = FilterClass.recursionBase(source, "id", "pid", "children");
console.log(data);
// //[{id:1,pid:0,name:"test",children:[{id:3,pid:1,name:"test"}]},{id:2,pid:0,name:"test"}]
```

### removeObjectAttribut **(移除对象里的属性)**

```javascript
/**
 * 移除对象里的属性
 * @param {Object} source 对象
 * @param {String} attributName 属性名
 */
rovemObjectAttribut(source, attributName);
```

```javascript
import { FilterClass } from "dl-utils";

let source = { id: 1, name: "小明" };
let attributName = "id";

let data = FilterClass.rovemObjectAttribut(source, attributName);

console.log(data);
// { name: '小明' }
```

### removeListAttribut **(移除对象里的属性)**

```javascript
/**
 * 移除对象数组里的属性
 * @param {Array} data 数组
 * @param {String} attributName 属性名
 */
rovemListAttribut(source, attributName);
```

```javascript
import { FilterClass } from "dl-utils";

let source = [
  { id: 1, name: "小明" },
  { id: 2, name: "小红" },
];
let attributName = "id";

let data = FilterClass.rovemListAttribut(source, attributName);

console.log(data);
// [ { name: '小明' }, { name: '小红' } ]
```

### replaceStringByArray **(替换字符串数组里的指定值)**

```javascript
/**
 * 替换字符串数组里的指定值,支持正则表达式
 * @param {Array} source 字符串数组 ['a','b','c',...]
 * @param {String} sourceString 原来的值
 * @param {String} targetString 替换的值 默认为'' (移除指定部分字符串)
 */
replaceStringByArray(source, sourceString, targetString);
```

```javascript
import { FilterClass } from "dl-utils";

let source = [
  { id: 1, name: "小明" },
  { id: 2, name: "小红" },
];
let sourceString = "name";
let targetString = "未名用户";

let data = FilterClass.replaceStringByArray(source, sourceString, targetString);

console.log(data);
// [{id:1,name:'未名用户'},{id:2,name:'未名用户'} ]
```

### appendAttributeByList **(在对象数组里追加属性和值)**

```javascript
/**
 * 在对象数组里追加属性和值
 * @param {Array} source 源数据 [{id:1},{id:2}]
 * @param {Object} target 目标数据 {type:"default"}
 * @returns {Array} [{id:1,type:"default"},{id:2,type:"default"}]
 */
appendAttributeByList(source, target);
```

```javascript
import { FilterClass } from "dl-utils";

let source = [
  { id: 1, name: "小明" },
  { id: 2, name: "小红" },
];
let target = { type: "user" };

let data = FilterClass.appendAttributeByList(source, target);

console.log(data);
// [ { id:1 , name: '小明',type:'user'}, {id:2 , name: '小红',type:'user'} ]
```

## CalendarClass 【日历工具】

### getCalendarList **(获取日历列表)**

**getCalendarList（date[Date]=日期 ，target[Nunber]=获取日期列表数，callback[Function]=回调 ）**

getCalendarList(date,{count,offset},callback){

```javascript
import { CalendarClass } from "dl-utils";

/**
/**
   * 获取日历对象集合
   * @param date 日期  
   * @param {Object} config { @param {number} count 行数 @param {number} offset 偏移量 默认为周一开始，如果需要按周日开始 可以偏移1  }
   * @param custom 自定义参数
   */
let list = CalendarClass.getCalendarList(new Date(), 42, (options) => {
  if (options.type === "now") {
    options.name = "1";
  } else {
    options.name = "2";
    options.dateFormat = "2020-12-27";
  }
  return options;
});
console.log(list);
// [{ day: 27, timestamp:1611713253868,month:12,dateFormat:'2020-12-27',type:'now',name:"1"},...]

// 获取当前月的天数
let day = CalendarClass.getMonthCount(new Date());

// 获取下个月的天数
let day1 = CalendarClass.getNextMonthCount(new Date());

// 获取上个月的天数
let day2 = CalendarClass.getPreMonthCount(new Date());

// 获取本月最后一天
let lastDay = CalendarClass.getMonthLastDay(new Date());

// 获取本月第一天
let firstDay = CalendarClass.getMonthFirstDay(new Date());
```

## CountDownClass 【倒计时】

### getCountDown **(获取当前时间和未来的时间差)**

```javascript
/**
 * 获取当前时间和未来的时间差
 * @param {Date || Number} endTime 【必填】 结束日期时间, 时间戳||日期时间（2021-02-01 10:00:00）
 * @param {Date || Number} startTime 【选填】 当前日期时间（默认为系统时间） 时间戳||日期时间（2021-02-01 10:00:00）
 * @returns {Object} 年，月，日，时，分，秒，时间戳
 */
getCountDown(endTime, startTime);
```

```javascript
import { CountDownClass } from "dl-utils";

let dateTime = "2021-03-10 00:00:00";

console.log(CountDownClass.getCountDown(dateTime));
// { dd: 55, hh: 5, mm: 45, ss: 5, ms: 282, timestamp: 4772705282000 }
```

### getCustomCountDown **(获取自定义倒计时 （不依赖当前系统时间）)**

```javascript
/**
 * 获取自定义倒计时（不依赖当前系统时间）
 * @param {Date} stratTime 服务器开始时间  时间搓 或 Date 实例
 * @param {Date} endTime 服务器结束时间 时间搓 或 Date 实例
 * @param {Function} callback 回调返回  return {hh,mm,ss}
 */
getCustomCountDown(stratTime, endTime, callback);
```

```javascript
import { CountDownClass } from "dl-utils";

let nowT = 1610789672692;
let newT = 1610796872692;

CountDownClass.getCustomCountDown(nowT, newT, function (obj) {
  console.log(obj); // { hh: 1, mm: 59, ss: 59 }
});
```

### clearAll

**(移除所有定时器)**

```javascript
/**
 * 移除所有定时器
 */
clearAll();
```

```javascript
import { CountDownClass } from "dl-utils";
CountDownClass.clearAll();
```

## RandomClass 【随机】

### getRandomNum**（获取随机整数）**

```javascript
/**
 * 获取随机整数（包括最大数和最小数）
 * @param {Number} Min 最小数
 * @param {Number} Max 最大数
 * @returns 随机数
 */
getRandomNum(Min, Max, Length);
```

```javascript
import { RandomClass } from "dl-utils";

console.log(RandomClass.getRandomNum(1, 100, 4));
// [ 93, 62, 97, 12 ]
```

### getRandomLetter **(获取随机字符串)**

```javascript
/**
 * 获取随机字符串
 * @param {Number} Length 生成字符串的长度
 * @returns 随机字符串
 */
getRandomLetter(Length);
```

```javascript
import { RandomClass } from "dl-utils";

console.log(RandomClass.getRandomLetter(4));
// MHbf
```

### getRandomChar **(获取随机混合字符串)**

```javascript
/**
  * 获取随机混合字符串
  * @param {Number} Length 生成字符串的长度
  * @returns 随机混合字符串
  */
getRandomChar（Length）
```

```javascript
import { RandomClass } from "dl-utils";

console.log(RandomClass.getRandomChar(3));
// 7FX
```

### getRandomColor**(获取随机颜色)**

```java
/**
 * 获取随机颜色
 * @param {Number} min 最小颜色值 Default = 40
 * @param {Number} max 最大颜色值 Default = 180
 * @param {Number} opacity 透明度 Default = 1
 * @returns 随机的 rgb(?,?,?,?)
 */
getRandomColor(min,max,opacity)
```

```javascript
import { RandomClass } from "dl-utils";

console.log(RandomClass.getRandomColor(60, 120, 1));
// rgb(64,63,115,1)
```

---
_Source: https://npm.io/package/dl-utils · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
