# qyh_utils

> 公共方法工具库

Latest version **1.0.26** (published 2023-06-03) · MIT license · 0 weekly downloads

## Install

```sh
npm install qyh_utils
pnpm add qyh_utils
yarn add qyh_utils
bun add qyh_utils
```

## Health

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

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.26 |
| Published | 2023-06-03 |
| First published | 2023-05-28 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Node | 16.x |
| Dependencies | 0 |
| Unpacked size | 173.5 KB |
| Known vulnerabilities | 0 |
| Install scripts | yes |
| Author | 一个小瘪三 |
| Maintainers | qiqi-meom |
| Keywords | 工具库, utils, jest, typescript, rollup |

## Links

- npm: https://www.npmjs.com/package/qyh_utils
- Repository: https://gitee.com/menon-qiqi/qyh_utils
- npm.io page: https://npm.io/package/qyh_utils

## Alternatives

- [@openai/codex-sdk](https://npm.io/package/@openai/codex-sdk.md) — 731.4K weekly downloads
- [babel-plugin-transform-react-jsx](https://npm.io/package/babel-plugin-transform-react-jsx.md) — 565.0K weekly downloads
- [babel-helper-remove-or-void](https://npm.io/package/babel-helper-remove-or-void.md) — 508.5K weekly downloads
- [@pnpm/store-controller-types](https://npm.io/package/@pnpm/store-controller-types.md) — 186.9K weekly downloads
- [react-native-signature-canvas](https://npm.io/package/react-native-signature-canvas.md) — 155.6K weekly downloads

## Recent versions

- 1.0.26 (latest) — 2023-06-03
- 1.0.25 — 2023-06-02
- 1.0.24 — 2023-06-02
- 1.0.23 — 2023-06-02
- 1.0.21 — 2023-05-31
- 1.0.20 — 2023-05-31
- 1.0.19 — 2023-05-30
- 1.0.10 — 2023-05-29
- 1.0.9 — 2023-05-29
- 1.0.8 — 2023-05-29
- 1.0.7 — 2023-05-29
- 1.0.6 — 2023-05-29
- 1.0.5 — 2023-05-29
- 1.0.4 — 2023-05-28
- 1.0.1 — 2023-05-28

## README

- [安装](#安装)
- [EventBus](#eventbus)
  - [Typescript](#typescript)
- [ImageCompressor](#imagecompressor)
  - [配置项](#配置项)
- [otherfunction](#otherfunction)
  - [array2Tree](#array2tree)
  - [tree2Array](#tree2array)
  - [arrMapObj](#arrmapobj)
  - [deepClone](#deepclone)
  - [observerImg](#observerimg)
  - [control](#control)
## 安装

```javascript
$ npm i qyh_utils
```
****
## EventBus

```javascript
import {EventBus} from "qyh_utils"
const emmiter=new EventBus()
// 监听事件
emitter.on('foo', e => console.log('foo', e) )

// 派发事件
emitter.emit('foo', { a: 'b' })

// 清除所有事件
emitter.off()

// 清除同名事件
emitter.off("foo")

// 清除指定事件
emitter.off("foo",onFoo)
```

### Typescript

```ts
interface Events {
  foo: string
  bar?: number
}
const emitter = new EventBus<Events>()

emitter.on('foo', (e) => {}) // 'e' has inferred type 'string'

emitter.emit('foo', 42) // Error: Argument of type 'number' is not assignable to parameter of type 'string'. (2345)
```
****
## ImageCompressor
```javascript
import {ImageCompressor} from "qyh_utils"
import type {ImageCompressorOptions,IFile} from "qyh_utils"

const options:ImageCompressorOptions = {
  file: file,
  quality: 0.6,
  mimeType: 'image/jpeg',
  maxWidth: 500,
  maxHeight: 500,
  width: 200,
  height: 200,
  minWidth: 100,
  minHeight: 100,
  convertSize: Infinity,
  loose: true,
  redressOrientation: true,
  // 图片绘画前
  beforeDraw: function (ctx:CanvasRenderingContext2D) {
    console.log('准备绘图...');
    ctx.filter = 'grayscale(100%)';
  },

  // 图片绘画后
  afterDraw: function (ctx:CanvasRenderingContext2D, canvas:HTMLCanvasElement) {
    ctx.restore();
    console.log('绘图完成...');
    ctx.fillStyle = '#fff';
    ctx.font = (canvas.width * 0.1) + 'px microsoft yahei';
    ctx.fillText("qyh", 10, canvas.height - 20);
  },
  // 压缩前回调
  beforeCompress: function (result:IFile) {
    console.log('压缩之前图片尺寸大小: ', result.size);
    console.log('mime 类型: ', result.type);
  },

  // 压缩成功回调
  success: function (result:IFile) {
    const url = URL.createObjectURL(result)
    console.log('压缩之后图片尺寸大小: ', result.size);
    console.log('mime 类型: ', result.type);
    console.log('实际压缩率： ', ((file.size - result.size) / file.size * 100).toFixed(2) + '%');
  },

  // 发生错误
  error: function (msg:string) {
    console.error(msg);
  }
};

new ImageCompressor(options);
```
### 配置项

|         Name         | Type         | Default   | Description                                                                      |
| :------------------: | ------------ | --------- | -------------------------------------------------------------------------------- |
|        `file`        | `File  Blob` | `""`      | (必传项) 文件                                                                    |
|      `quality`       | `number`     | `0.8`     | 自定义配置压缩比                                                                 |
|      `mimeType`      | `string`     |           | 输出图片类型                                                                     |
|    `convertSize`     | `number`     | `2048000` | png转jpeg阈值                                                                    |
|       `width`        | `number`     |           | 宽度                                                                             |
|       `height`       | `number`     |           | 高度                                                                             |
|      `maxWidth`      | `number`     |           | 最大宽度                                                                         |
|     `maxHeight`      | `number`     |           | 最大高度                                                                         |
|      `minWidth`      | `number`     |           | 最小宽度                                                                         |
|     `minHeight`      | `number`     |           | 最小高度                                                                         |
| `redressOrientation` | `boolean`    |           | 是否矫正jpeg方向                                                                 |
|       `loose`        | `boolean`    | `true`    | 是否宽松模式（控制当压缩的图片 size 大于源图片，输出源图片，否则输出压缩后图片） |
****
## otherfunction
### array2Tree
```javascript
import {array2Tree} from "qyh_utils"
const arr = [
  {
    name: '中国',
    id: 1,
    al: 'xx',
    parentId: 0,
  },
  {
    name: '北京',
    al: 'xx',
    id: 2,
    parentId: 1,
  },
  {
    name: '上海',
    al: 'xx',
    id: 3,
    parentId: 2,
  },
  {
    name: '台湾',
    al: 'xx',
    id: 4,
    parentId: 3,
  },
  {
    name: '钓鱼岛',
    id: 5,
    al: 'xx',
    parentId: 4,
  },
]
const tree=array2Tree(arr)
```
### tree2Array
```javascript
import {tree2Array} from "qyh_utils"
const tree = {
  name: '中国',
  id: 1,
  al: 'xx',
  parentId: 0,
  children: [
    {
      name: '北京',
      al: 'xx',
      id: 2,
      parentId: 1,
      children: [
        {
          name: '上海',
          al: 'xx',
          id: 3,
          parentId: 2,
          children: [
            {
              name: '台湾',
              al: 'xx',
              id: 4,
              parentId: 3,
              children: [
                {
                  name: '钓鱼岛',
                  id: 5,
                  al: 'xx',
                  parentId: 4,
                },
              ],
            },
          ],
        },
      ],
    },
  ],
}
const array=array2Tree(tree)
```
### arrMapObj
```javascript
import {arrMapObj} from "qyh_utils"
const arr=[{ id: '1', name: 'zs' }, { id: '2', name: 'ls' }]
const obj= arrMapObj(arr,"id")
//  {
//     1: { id: '1', name: 'zs' },
//     2: { id: '2', name: 'ls' },
//  }
```
### deepClone
```javascript
import {deepClone} from "qyh_utils"
  let info = { item: 1 };
  let obj: Record<string, any> = {
    key1: info,
    key2: info,
    list: [1, 2]
  };

  // 循环引用深拷贝示例
  obj.key3 = obj;
  let cloneObj = deepClone(obj);
  console.log("obj", obj);
  console.log("cloneObj", cloneObj);
```
### observerImg
```javascript
import {observerImg} from "qyh_utils"
// 图片懒加载 IntersectionObserver
  observerImg()
```
### control
```javascript
import {control} from "qyh_utils"
// 控制最大并发
   function task1() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve("task1");
        console.log("task1")
      })
    });
  }
  function task2() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve("task2");
        console.log("task2")
      }, 1000);
    });
  }
  function task3() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve("task3");
        console.log("task3")
      }, 20);
    });
  }
  function task4() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve("task4");
        console.log("task4")
      }, 500);
    });
  }
  function task5() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve("task5");
        console.log("task5")
      }, 2000);
    });
  }
  const tasks = [task1, task2, task3, task4, task5];
  control(tasks, 2)
```

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