common-utils-kit 1.0.5 → 1.0.6

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/index.js CHANGED
@@ -2,10 +2,12 @@
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
+ console.log(' ', test.hasValue(0))
6
7
  export default {
7
8
  test: { test },
8
9
  format: { format },
9
- tool: { tool }
10
+ tool: { tool },
11
+ files: { files }
10
12
  }
11
13
  // 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.6",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "type": "module",
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
@@ -3,6 +3,16 @@
3
3
  * @param {Object} obj - 要获取属性值的对象
4
4
  * @param {string} key - 属性路径,可以包含点号('.')表示深层嵌套属性
5
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!
6
16
  */
7
17
  export function getProperty(obj, key) {
8
18
  if (!obj) { return }
@@ -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,38 @@ export function flatToTree(flatArray, rootValue = null, bind = "pid") {
83
134
  });
84
135
  return tree.length > 0 ? tree : null; // 处理不存在的根节点
85
136
  }
137
+ /**
138
+ * 递归封装
139
+ * @param {Array} data - 待处理的数据
140
+ * @param {Function} funName - 处理每个节点的方法
141
+ * @param {string} [bind="children"] - 子节点绑定属性的名称,默认为 "children"
142
+ * @returns {Array} - 处理后的树形结构数据
143
+ * @example
144
+ * // 数据结构
145
+ * const treeData = [{ id: 1,
146
+ * label: 'parent 1',
147
+ * children: [{ id: 2, label: 'child 1' },{ id: 3, label: 'child 2' }]
148
+ * },{id: 4,
149
+ * label: 'parent 2',
150
+ * children: [{ id: 5, label: 'child 3' },{ id: 6, label: 'child 4' }]
151
+ * }];
152
+ *
153
+ * // 处理逻辑函数,
154
+ * function processFunction(node) {
155
+ * return { label: node.label.toUpperCase() };
156
+ * }
157
+ * // 使用递归封装方法
158
+ * const processedTree = recursionFunction(treeData, processFunction);
159
+ */
160
+ export function recursionFunction(data, processFunction, bind = 'children') {
161
+ function internalRecursion(previous, initial) {
162
+ return previous.map((element, i) => {
163
+ const menus = initial[i] ? processFunction(initial[i]) : {};
164
+ const children = element[bind] && Array.isArray(element[bind]) && element[bind].length > 0
165
+ ? internalRecursion(element[bind], initial[i][bind])
166
+ : [];
167
+ return { [bind]: children, ...menus };
168
+ });
169
+ }
170
+ return internalRecursion(data, data);
171
+ }
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) {