common-utils-kit 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,5 +13,6 @@ import {test,format,tool} from "common-utils-kit/src/test";
13
13
  test //验证数据类型 例:test.number(1)
14
14
  format // 格式化数据 例:
15
15
  tool //工具函数
16
+ files //文件下载
16
17
  ```
17
18
 
package/index.js CHANGED
@@ -2,10 +2,14 @@
2
2
  import * as test from './src/test.js';
3
3
  import * as format from './src/format.js';
4
4
  import * as tool from './src/tool.js';
5
- console.log(' ', tool.antiShake())
5
+ import * as files from './src/files.js';
6
+ import directive from './src/directive.js';
7
+ console.log(' ', test.hasValue(0))
6
8
  export default {
7
9
  test: { test },
8
10
  format: { format },
9
- tool: { tool }
11
+ tool: { tool },
12
+ files: { files },
13
+ directive:directive
10
14
  }
11
15
  // https://www.cnblogs.com/oldCode/p/learnjts.html
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "common-utils-kit",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -0,0 +1,225 @@
1
+ // import ElTableInfiniteScroll from "el-table-infinite-scroll";
2
+ // 自定义指令基础配置
3
+ const directives = {
4
+ inputDebounce: { // 输入框防抖
5
+ inserted: function (el, binding) {
6
+ const fn = binding.value;
7
+ const time = binding.arg || 500;
8
+ let timer;
9
+ let flag = true; // 输入法标记
10
+ el.addEventListener("compositionstart", () => { // 监听中文输入开始
11
+ flag = false;
12
+ });
13
+ el.addEventListener("compositionend", () => { // 监听中文输入结束
14
+ flag = true;
15
+ });
16
+ el.addEventListener('input', () => {
17
+ timer && clearTimeout(timer);
18
+ timer = setTimeout(() => {
19
+ if (flag) fn();
20
+ }, time);
21
+ });
22
+ },
23
+ },
24
+ btnDebounce: { // 按钮防抖
25
+ inserted: (el, binding) => {
26
+ const time = binding.arg || 1000; // 防抖时间
27
+ let debounce = null;
28
+ el.addEventListener('click', event => {
29
+ if (debounce !== null) {
30
+ clearTimeout(debounce)
31
+ event && event.stopImmediatePropagation();
32
+ }
33
+ debounce = setTimeout(() => {
34
+ debounce = null
35
+ }, time)
36
+ }, true);
37
+ }
38
+ },
39
+ btnThrottle: { // 按钮节流
40
+ inserted: (el, binding) => {
41
+ const time = binding.arg || 1000; // 间隔时间
42
+ let cbFun;
43
+ el.addEventListener('click', event => {
44
+ if (!cbFun) { // 第一次执行
45
+ cbFun = setTimeout(() => {
46
+ cbFun = null;
47
+ }, time);
48
+ } else {
49
+ event && event.stopImmediatePropagation();
50
+ }
51
+ }, true);
52
+ }
53
+ },
54
+ relativeTime: { // 时间转换
55
+ bind(el, binding) {
56
+ var intervalTime = 60000
57
+ var Time = {
58
+ getUnix: function () { // 获取当前时间戳
59
+ var date = new Date();
60
+ return date.getTime();
61
+ },
62
+ getTodayUnix: function () { // 获取今天0点0分0秒的时间戳
63
+ var date = new Date();
64
+ date.setHours(0);
65
+ date.setMinutes(0);
66
+ date.setSeconds(0);
67
+ date.setMilliseconds(0);
68
+ return date.getTime();
69
+ },
70
+ getYearUnix: function () { // 获取今年1月1日0点0分0秒的时间戳
71
+ var date = new Date();
72
+ date.setMonth(0);
73
+ date.setDate(1);
74
+ date.setHours(0);
75
+ date.setMinutes(0);
76
+ date.setSeconds(0);
77
+ date.setMilliseconds(0);
78
+ return date.getTime();
79
+ },
80
+ getLastDate: function () { // 获取标准年月日
81
+ var date = new Date();
82
+ var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
83
+ var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
84
+ return date.getFullYear() + '-' + month + '-' + day;
85
+ },
86
+ getFormatTime: function (timestamp) { // 转换时间
87
+ var now = this.getUnix();// 当前时间戳
88
+ var today = this.getTodayUnix();// 今天0点时间戳
89
+ var timer = (now - timestamp) / 1000;// 转换为妙级别时间戳
90
+ var tip = '';
91
+ if (timer <= 0) {
92
+ tip = '刚刚';
93
+ } else if (Math.floor(timer / 60) <= 0) {
94
+ tip = '刚刚';
95
+ } else if (timer < 3600) {
96
+ tip = Math.floor(timer / 60) + '分钟前';
97
+ } else if (timer >= 3600 && (timestamp - today >= 0)) {
98
+ tip = Math.floor(timer / 3600) + '小时前';
99
+ intervalTime = 3600000;
100
+ } else if (timer / 86400 <= 31) {
101
+ tip = Math.ceil(timer / 86400) + '天前';
102
+ intervalTime = 3600000 * 24;
103
+ } else {
104
+ tip = this.getLastDate(timestamp);
105
+ intervalTime = 3600000 * 24;
106
+ }
107
+ return tip;
108
+ }
109
+ }
110
+ el.innerHTML = Time.getFormatTime(binding.value)
111
+ el.__timeout__ = setInterval(() => {
112
+ el.innerHTML = Time.getFormatTime(binding.value)
113
+ }, intervalTime)
114
+ },
115
+ unbind(el) {
116
+ clearInterval(el.innerHTML)
117
+ delete el.__timeout__
118
+ }
119
+ },
120
+ replace: {//限制input输入内容
121
+ inserted: function (el, binding, vnode) {
122
+ const element = el.tagName === "INPUT" ? el : el.querySelector("input");
123
+ let flag = true; // 输入法标记
124
+ element.addEventListener("compositionstart", () => {
125
+ flag = false;
126
+ }); // 监听中文输入开始
127
+ element.addEventListener("compositionend", () => {
128
+ flag = true;
129
+ }); // 监听中文输入结束
130
+ element.addEventListener("keyup", () => {
131
+ // 监听中文输入结束
132
+ if (flag) {
133
+ switch (binding.arg) {
134
+ case "price": // 正负的两位小数金额 -和.只能出现一次 并且-只能在首位
135
+ element.value = element.value.replace(/^([-+])?\D*(\d*(?:\.\d{0,2})?).*$/, "$1$2");
136
+ break;
137
+ case "+price": // 验证正的两位小数金额
138
+ element.value = element.value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, "$1");
139
+ break;
140
+ case "num": // 只能输入正整数
141
+ element.value = element.value.replace(/[^\d]|^[0]/g, "");
142
+ break;
143
+ case "natural": // 只能输入自然数
144
+ element.value = element.value.replace(/[^\d]/g, "");
145
+ break;
146
+ }
147
+ }
148
+ });
149
+ },
150
+ },
151
+ elDragDialog: {
152
+ bind(el, binding, vnode) {
153
+ const dialogHeaderEl = el.querySelector('.el-dialog__header')
154
+ const dragDom = el.querySelector('.el-dialog')
155
+ dialogHeaderEl.style.cssText += ';cursor:move;'
156
+ dragDom.style.cssText += ';top:0px;'
157
+ // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
158
+ const getStyle = (function () {
159
+ if (window.document.currentStyle) {
160
+ return (dom, attr) => dom.currentStyle[attr]
161
+ } else {
162
+ return (dom, attr) => getComputedStyle(dom, false)[attr]
163
+ }
164
+ })()
165
+ dialogHeaderEl.onmousedown = (e) => {
166
+ // 鼠标按下,计算当前元素距离可视区的距离
167
+ const disX = e.clientX - dialogHeaderEl.offsetLeft
168
+ const disY = e.clientY - dialogHeaderEl.offsetTop
169
+ const dragDomWidth = dragDom.offsetWidth
170
+ const dragDomHeight = dragDom.offsetHeight
171
+ const screenWidth = document.body.clientWidth
172
+ const screenHeight = document.body.clientHeight
173
+ const minDragDomLeft = dragDom.offsetLeft
174
+ const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth
175
+ const minDragDomTop = dragDom.offsetTop
176
+ const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomHeight
177
+ // 获取到的值带px 正则匹配替换
178
+ let styL = getStyle(dragDom, 'left')
179
+ let styT = getStyle(dragDom, 'top')
180
+ if (styL.includes('%')) {
181
+ styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100)
182
+ styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100)
183
+ } else {
184
+ styL = +styL.replace(/\px/g, '')
185
+ styT = +styT.replace(/\px/g, '')
186
+ }
187
+ document.onmousemove = function (e) {
188
+ // 通过事件委托,计算移动的距离
189
+ let left = e.clientX - disX
190
+ let top = e.clientY - disY
191
+ // 边界处理
192
+ if (-(left) > minDragDomLeft) {
193
+ left = -minDragDomLeft
194
+ } else if (left > maxDragDomLeft) {
195
+ left = maxDragDomLeft
196
+ }
197
+ if (-(top) > minDragDomTop) {
198
+ top = -minDragDomTop
199
+ } else if (top > maxDragDomTop) {
200
+ top = maxDragDomTop
201
+ }
202
+ // 移动当前元素
203
+ dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`
204
+ // emit onDrag event
205
+ vnode.child.$emit('dragDialog')
206
+ }
207
+ document.onmouseup = function (e) {
208
+ document.onmousemove = null
209
+ document.onmouseup = null
210
+ }
211
+ }
212
+ }
213
+ },
214
+
215
+ }
216
+ // 批量注册自定义指令
217
+ export default {
218
+ install(Vue) {
219
+ Object.keys(directives).forEach((key) => {
220
+ const name = key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
221
+ Vue.directive(name, directives[key]);
222
+ });
223
+ },
224
+ };
225
+
package/src/files.js ADDED
@@ -0,0 +1,109 @@
1
+ /**
2
+ * 下载 base64 编码的文件
3
+ * @param {string} url - base64 编码的数据
4
+ * @param {string} type - 文件类型的后缀名
5
+ * @param {string} name - 文件名
6
+ * @returns {Promise<string>} - Promise 对象,包含文件下载成功时的消息或失败时的错误信息
7
+ * @example
8
+ * const base64Data = "data:image/png;base64,R0lGODlhHAAmAKIHAKqqqsvLy0hISObm5vf394uLiwAAAP///yH5B…EoqQqJKAIBaQOVKHAXr3t7txgBjboSvB8EpLoFZywOAo3LFE5lYs/QW9LT1TRk1V7S2xYJADs=";
9
+ * downloadBase64File(base64Data, "png", "myImage").then((message) => {
10
+ * console.log(message); // 文件下载成功
11
+ * }).catch((error) => {
12
+ * console.error(error); // 文件下载失败或其他错误信息
13
+ * });
14
+ */
15
+ export function downloadBase64File(url, type = "pdf", name = "文件" + Date.now()) {
16
+ return new Promise((resolve, reject) => {
17
+ if (!url) return reject('文件不存在');
18
+ const imgType = ["png", "jpg", "gif", "jpeg", "webp", "bmp", "tif", "pcx", "tga", "exif", "fpx", "svg", "psd", "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "WMF",];
19
+ const createBlob = (data, mimeType) => {
20
+ try {
21
+ return new Blob([data], { type: mimeType });
22
+ } catch (e) {
23
+ reject('创建 Blob 失败');
24
+ }
25
+ };
26
+ let myBlob = null;
27
+ if (imgType.includes(type)) {
28
+ const arr = url.split(",");
29
+ const mime = arr[0].match(/:(.*?);/)[1];
30
+ const bstr = atob(arr[1]);
31
+ const u8arr = new Uint8Array(bstr.length);
32
+ let n = bstr.length;
33
+ for (let i = 0; i < bstr.length; i++) {
34
+ u8arr[i] = bstr.charCodeAt(i);
35
+ }
36
+ myBlob = createBlob(u8arr, mime);
37
+ } else {
38
+ const bstr = atob(url);
39
+ const u8arr = new Uint8Array(bstr.length);
40
+ for (let i = 0; i < bstr.length; i++) {
41
+ u8arr[i] = bstr.charCodeAt(i);
42
+ }
43
+ myBlob = createBlob(u8arr, type);
44
+ }
45
+ const myUrl = URL.createObjectURL(myBlob);
46
+ const a = document.createElement("a");
47
+ a.setAttribute("href", myUrl);
48
+ const fileName = name;
49
+ a.setAttribute("download", fileName);
50
+ a.setAttribute("target", "_blank");
51
+ const clickEvent = document.createEvent("MouseEvents");
52
+ clickEvent.initEvent("click", true, true);
53
+ a.addEventListener("click", () => {
54
+ window.requestAnimationFrame(() => {
55
+ setTimeout(() => {
56
+ URL.revokeObjectURL(myUrl);
57
+ resolve('文件下载成功');
58
+ }, 0);
59
+ });
60
+ });
61
+ a.dispatchEvent(clickEvent);
62
+ });
63
+ }
64
+ /**
65
+ * 文件地址下载文件
66
+ * @param {string} url - 文件地址
67
+ * @param {string} filename - 下载后的文件名
68
+ * @returns {Promise<boolean>} - Promise 对象,表示下载成功(true)或失败(false)
69
+ * @example
70
+ * const fileUrl = "https://example.com/file/document.pdf";
71
+ * const customFileName = "myDocument";
72
+ * downloadFiles(fileUrl, customFileName).then((message) => {
73
+ * console.log(message); // 文件下载成功
74
+ * }).catch((error) => {
75
+ * console.error(error); // 文件下载失败或其他错误信息
76
+ * });
77
+ */
78
+ export function downloadFiles(url, filename) {
79
+ return new Promise((resolve, reject) => {
80
+ const xhr = new XMLHttpRequest();
81
+ xhr.open("GET", url, true);
82
+ xhr.responseType = "blob";
83
+ xhr.onload = () => {
84
+ if (xhr.status === 200) {
85
+ const decodedUrl = decodeURIComponent(url);
86
+ const matches = decodedUrl.match(/\/([^\/?#]+)[^\/]*$/);
87
+ const newFileName = filename ? (filename.includes('.') ? filename : `${filename}.${matches[1].split('.').pop()}`) : matches[1]
88
+ if (window.navigator.msSaveOrOpenBlob) {
89
+ navigator.msSaveBlob(xhr.response, newFileName);
90
+ } else {
91
+ const link = document.createElement("a");
92
+ link.href = window.URL.createObjectURL(xhr.response);
93
+ link.download = newFileName;
94
+ link.style.position = "absolute";
95
+ link.style.opacity = "0";
96
+ link.style.pointerEvents = "none";
97
+ document.body.appendChild(link);
98
+ link.click();
99
+ document.body.removeChild(link);
100
+ window.URL.revokeObjectURL(link.href);
101
+ }
102
+ resolve("文件下载成功")
103
+ } else {
104
+ reject("文件下载失败")
105
+ }
106
+ };
107
+ xhr.send();
108
+ });
109
+ }
package/src/format.js CHANGED
@@ -1,9 +1,19 @@
1
1
  /**
2
- * 获取对象属性值,支持可选链操作符的形式
3
- * @param {Object} obj - 要获取属性值的对象
4
- * @param {string} key - 属性路径,可以包含点号('.')表示深层嵌套属性
5
- * @returns {*} - 返回属性值,如果属性不存在则返回 undefined
6
- */
2
+ * 获取对象属性值,支持可选链操作符的形式
3
+ * @param {Object} obj - 要获取属性值的对象
4
+ * @param {string} key - 属性路径,可以包含点号('.')表示深层嵌套属性
5
+ * @returns {*} - 返回属性值,如果属性不存在则返回 undefined
6
+ * @example
7
+ * const data = {
8
+ * parent: {
9
+ * child: {
10
+ * value: 'Hello, World!'
11
+ * }
12
+ * }
13
+ * };
14
+ * const nestedValue = getProperty(data, 'parent.child.value');
15
+ * console.log(nestedValue); // 输出: Hello, World!
16
+ */
7
17
  export function getProperty(obj, key) {
8
18
  if (!obj) { return }
9
19
  if (typeof key !== 'string' || key === '') {
@@ -27,6 +37,11 @@ export function getProperty(obj, key) {
27
37
  * @param {array} data 需要去重的原数组对象
28
38
  * @param {string} parameter 去重数组的唯一码(关键字)
29
39
  * @returns {Array} - 返回去重后的数组对象
40
+ * @example
41
+ * // 使用示例
42
+ * const data = [{ id: 1, name: 'John' },{ id: 2, name: 'Jane' },{ id: 1, name: 'John' },{ id: 3, name: 'Doe' }];
43
+ * const uniqueData = unrepeated(data, 'id');
44
+ * console.log(uniqueData); // 输出: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Doe' }]
30
45
  */
31
46
  export function unrepeated(data, parameter) {
32
47
  var temp = {};
@@ -46,6 +61,17 @@ export function unrepeated(data, parameter) {
46
61
  * @param {Array} previous - 树形结构数据
47
62
  * @param {string} bind - 树形结构中下级节点的绑定属性,默认为 'children'
48
63
  * @returns {Array} - 一维数组
64
+ * @example
65
+ * const treeData = [{ id: 1,
66
+ * label: 'parent 1',
67
+ * children: [{ id: 2, label: 'child 1' },{ id: 3, label: 'child 2' }]
68
+ * },{id: 4,
69
+ * label: 'parent 2',
70
+ * children: [{ id: 5, label: 'child 3' },{ id: 6, label: 'child 4' }]
71
+ * }];
72
+ * const flatArray = treeToFlat(treeData,'children');
73
+ * console.log(flatArray);
74
+ * // 输出:[ { id: 1, label: 'parent 1' },{ id: 2, label: 'child 1' }, { id: 3, label: 'child 2' }, { id: 4, label: 'parent 2' },{ id: 5, label: 'child 3' },{ id: 6, label: 'child 4' }]
49
75
  */
50
76
  export function treeToFlat(previous, bind = 'children') {
51
77
  const result = []
@@ -69,6 +95,31 @@ export function treeToFlat(previous, bind = 'children') {
69
95
  * @param {string} [rootValue=null] - 树形结构一级父 id,默认为 null
70
96
  * @param {string} [bind="pid"] - 父 id 的属性,默认为 "pid"
71
97
  * @returns {Array} - 树形结构
98
+ * @example
99
+ * const flatArray = [
100
+ * { id: 1, label: 'Node 1', pid: null },
101
+ * { id: 2, label: 'Node 2', pid: 1 },
102
+ * { id: 3, label: 'Node 3', pid: 1 },
103
+ * { id: 4, label: 'Node 4', pid: 2 },
104
+ * { id: 5, label: 'Node 5', pid: 2 },
105
+ * { id: 6, label: 'Node 6', pid: 3 },
106
+ * { id: 7, label: 'Node 7', pid: null },
107
+ * { id: 8, label: 'Node 8', pid: 3 },
108
+ * ];
109
+ * const treeData = flatToTree(flatArray);
110
+ * console.log(treeData);
111
+ * // 输出: [
112
+ * // {
113
+ * // id: 1,
114
+ * // label: 'Node 1',
115
+ * // pid: null,
116
+ * // children: [
117
+ * // { id: 2, label: 'Node 2', pid: 1, children: [ { id: 4, label: 'Node 4', pid: 2 }, { id: 5, label: 'Node 5', pid: 2 } ] },
118
+ * // { id: 3, label: 'Node 3', pid: 1, children: [ { id: 6, label: 'Node 6', pid: 3, children: [ { id: 8, label: 'Node 8', pid: 6 } ] } ] },
119
+ * // ],
120
+ * // },
121
+ * // { id: 7, label: 'Node 7', pid: null },
122
+ * // ]
72
123
  */
73
124
  export function flatToTree(flatArray, rootValue = null, bind = "pid") {
74
125
  const tree = [];
@@ -83,3 +134,72 @@ export function flatToTree(flatArray, rootValue = null, bind = "pid") {
83
134
  });
84
135
  return tree.length > 0 ? tree : null; // 处理不存在的根节点
85
136
  }
137
+
138
+ /**
139
+ * 递归封装
140
+ * @param {Array} data - 待处理的数据
141
+ * @param {Function} funName - 处理每个节点的方法
142
+ * @param {string} [bind="children"] - 子节点绑定属性的名称,默认为 "children"
143
+ * @returns {Array} - 处理后的树形结构数据
144
+ * @example
145
+ * // 数据结构
146
+ * const treeData = [{ id: 1,
147
+ * label: 'parent 1',
148
+ * children: [{ id: 2, label: 'child 1' },{ id: 3, label: 'child 2' }]
149
+ * },{id: 4,
150
+ * label: 'parent 2',
151
+ * children: [{ id: 5, label: 'child 3' },{ id: 6, label: 'child 4' }]
152
+ * }];
153
+ *
154
+ * // 处理逻辑函数,
155
+ * function processFunction(node) {
156
+ * return { label: node.label.toUpperCase() };
157
+ * }
158
+ * // 使用递归封装方法
159
+ * const processedTree = recursionFunction(treeData, processFunction);
160
+ */
161
+ export function recursionFunction(data, processFunction, bind = 'children') {
162
+ function internalRecursion(previous, initial) {
163
+ return previous.map((element, i) => {
164
+ const menus = initial[i] ? processFunction(initial[i]) : {};
165
+ const children = element[bind] && Array.isArray(element[bind]) && element[bind].length > 0
166
+ ? internalRecursion(element[bind], initial[i][bind])
167
+ : [];
168
+ return { [bind]: children, ...menus };
169
+ });
170
+ }
171
+ return internalRecursion(data, data);
172
+ }
173
+
174
+ /**
175
+ * 解析给定函数中switch case语句中的数据并返回提取出值的数组对象。
176
+ * @param {function} filterMethod - 包含带有条件和标签的 case 的函数。
177
+ * @returns {Array} - 包含提取出的值和标签的对象数组。
178
+ * @example
179
+ * const filterMethod = (item) => {
180
+ * switch (item) {
181
+ * case 1://若是字符串请使用单引号
182
+ * return "是";
183
+ * case 2://若是字符串请使用单引号
184
+ * return "否";
185
+ * default:
186
+ * return "数据异常";
187
+ * }
188
+ * };
189
+ * 使用
190
+ * filterData(filterMethod)//[{label:"是",value:1},{label:"否",value:2}]
191
+ */
192
+ export function filterData(filterMethod) {
193
+ const funStrArr = filterMethod.toString().split("case");
194
+ if (funStrArr.length < 1) return []
195
+ const list = [];
196
+ for (let i = 1; i < funStrArr.length; i++) {
197
+ const condition = funStrArr[i].split(":")[0].replace(/\s*/g, "").replace(/(\"*)/g, "");
198
+ const value = JSON.parse(condition.replace(/'/g, '"'))
199
+ const label = funStrArr[i].split("return")[1].split(";")[0].replace(/\s*/g, "").replace(/(\"*)/g, "");
200
+ if (value || value === 0 || value === false) {
201
+ list.push({ value, label });
202
+ }
203
+ }
204
+ return list;
205
+ }
package/src/test.js CHANGED
@@ -4,6 +4,15 @@
4
4
  * @param {*} value - 要验证的值
5
5
  * @param {string} type - 类型检查(可选),当类型为 'number' 时会将 0 视为有值
6
6
  * @returns {boolean} - 如果有值返回 true,否则返回 false
7
+ * @example
8
+ * // 使用示例
9
+ * console.log(hasValue(' Hello ')); // 输出: true
10
+ * console.log(hasValue(0, 'number'),hasValue(0)); // 传入类型number,0也是有值 输出: true false
11
+ * console.log(hasValue(true)); // 输出: true
12
+ * console.log(hasValue([1, 2, 3]),hasValue([])); // 输出: true false
13
+ * console.log(hasValue({ key: 'value' }),hasValue({})); // 输出: true false
14
+ * console.log(hasValue(undefined)); // 输出: false
15
+ * console.log(hasValue(null)); // 输出: false
7
16
  */
8
17
  export function hasValue(value, type) {
9
18
  switch (typeof value) {
@@ -29,6 +38,15 @@ export function hasValue(value, type) {
29
38
  * 获取值的数据类型
30
39
  * @param {*} value - 要获取类型的值
31
40
  * @returns {string} - 返回值的数据类型,包括 'string'、'number'、'boolean'、'function'、'array'、'object'、'null' 等
41
+ * @example
42
+ * // 使用示例
43
+ * console.log(valueType('Hello')); // 输出: 'string'
44
+ * console.log(valueType(42)); // 输出: 'number'
45
+ * console.log(valueType(true)); // 输出: 'boolean'
46
+ * console.log(valueType(function () {})); // 输出: 'function'
47
+ * console.log(valueType([1, 2, 3])); // 输出: 'array'
48
+ * console.log(valueType({ key: 'value' })); // 输出: 'object'
49
+ * console.log(valueType(null)); // 输出: 'null'
32
50
  */
33
51
  export function valueType(value) {
34
52
  switch (typeof value) {
package/src/tool.js CHANGED
@@ -38,3 +38,18 @@ export function throttle(time = 500) { //防抖 // 默认0.2秒后执行事件
38
38
  }, time)
39
39
  })
40
40
  }
41
+
42
+ /**
43
+ * @description 进行阻塞延时,以达到可以简写代码的目的
44
+ * @param {number} value 堵塞时间 单位ms 毫秒
45
+ * @returns {Promise} 返回promise
46
+ * @example
47
+ * await sleep(1000);
48
+ */
49
+ export function sleep(value = 100) {
50
+ return new Promise((resolve) => {
51
+ setTimeout(() => {
52
+ resolve()
53
+ }, value)
54
+ })
55
+ }