LOG // 052
常用工具函数
发布 2023-11-17炖制 7 天字数 4阅读 5 min
01图片压缩
ts
1// 压缩图片
2const compressImage = async (file: File, { quality = 1, type = file.type }) => {
3 // Get as image data
4 const imageBitmap = await createImageBitmap(file)
5
6 // Draw to canvas
7 const canvas = document.createElement('canvas')
8 canvas.width = imageBitmap.width
9 canvas.height = imageBitmap.height
10 const ctx = canvas.getContext('2d')
11 // @ts-ignore
12 ctx.drawImage(imageBitmap, 0, 0)
13
14 // Turn into Blob
15 const blob = await new Promise((resolve) => canvas.toBlob(resolve, type, quality))
16
17 // Turn Blob into File
18 const newFile = new File([blob as Blob], file.name, {
19 type: (blob as Blob).type
20 })
21 console.log('newFile', newFile)
22 return newFile
23}
02数组转树状结构
js
1// 数组转树状结构
2const list = [
3 {id: 1, text: 'aaa', parentId: null},
4 {id: 3, text: 'aaa', parentId: 1},
5 {id: 2, text: 'aaa', parentId: 1},
6 {id: 4, text: 'aaa', parentId: 2},
7 {id: 5, text: 'aaa', parentId: 2},
8 {id: 7, text: 'aaa', parentId: 3},
9 {id: 8, text: 'aaa', parentId: 4},
10 {id: 6, text: 'aaa', parentId: 6}
11]
12const obj = {};
13let root = {};
14list.map((el, i) => {
15obj[el.id] = i
16})
17//获取id与索引的映射
18console.log(obj)
19
20function format() {
21list.map((el, i) => {
22 if (!el.parentId) {
23 root = el;
24 return;
25 }
26 // 找到父级元素
27 const parentEl = list[obj[el.parentId]];
28 console.log(parentEl)
29 // 往父级元素添加本身作为子元素
30 parentEl.children = [...(parentEl.children || []), el];
31
32})
33console.log('root', root)
34}
35format()
03防抖
ts
1/*
2fn: 执行的函数;
3delay: 延迟时间;
4immediate: 是否立即执行函数
5*/
6let timer;
7function debounce(fn, delay, immediate) {
8 if(timer) clearTimeout(timer);
9 if(immediate) {
10 timer = setTimeout(() => {
11 timer = null;
12 }, delay)
13 if(!timer) fn.apply(this,arguments)
14 }else {
15 timer = setTimeout(() => {
16 fn.apply(this,arguments)
17 }, delay)
18 }
19
20}
21function fn() {
22 console.log('111')
23}
24
25for (let index = 0; index < 10; index++) {
26 console.log(index)
27 debounce(fn, 0)
28}
04节流
ts
1let flag = true
2function throttle(fn, delay) {
3 if(!flag) return;
4 flag = false;
5 setTimeout(() => {
6 fn.apply(this,arguments)
7 flag = true;
8 }, delay)
9}