index.js
8.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/**
* 格式化时间
* @param time
* @param cFormat
* @returns {string|null}
*/
import { JSEncrypt } from 'jsencrypt'
export function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
time = parseInt(time)
}
if (typeof time === 'number' && time.toString().length === 10) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay(),
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
/**
* 格式化时间
* @param time
* @param option
* @returns {string}
*/
export function formatTime(time, option) {
if (('' + time).length === 10) {
time = parseInt(time) * 1000
} else {
time = +time
}
const d = new Date(time)
const now = Date.now()
const diff = (now - d) / 1000
if (diff < 30) {
return '刚刚'
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return '1天前'
}
if (option) {
return parseTime(time, option)
} else {
return (
d.getMonth() +
1 +
'月' +
d.getDate() +
'日' +
d.getHours() +
'时' +
d.getMinutes() +
'分'
)
}
}
/**
* 将url请求参数转为json格式
* @param url
* @returns {{}|any}
*/
export function paramObj(url) {
const search = url.split('?')[1]
if (!search) {
return {}
}
const replacedSearch = decodeURIComponent(search)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')
.replace(/\+/g, ' ')
return JSON.parse(`{${replacedSearch}}`)
}
/**
* 父子关系的数组转换成树形结构数据
* @param data
* @returns {*}
*/
export function translateDataToTree(data) {
const parent = data.filter(
(value) => value.parentId === 'undefined' || value.parentId == null
)
const children = data.filter(
(value) => value.parentId !== 'undefined' && value.parentId != null
)
const translator = (parent, children) => {
parent.forEach((parent) => {
children.forEach((current, index) => {
if (current.parentId === parent.id) {
const temp = JSON.parse(JSON.stringify(children))
temp.splice(index, 1)
translator([current], temp)
typeof parent.children !== 'undefined'
? parent.children.push(current)
: (parent.children = [current])
}
})
})
}
translator(parent, children)
return parent
}
/**
* 树形结构数据转换成父子关系的数组
* @param data
* @param pathField 生成路径字段
* @returns {[]}
*/
export function translateTreeToData(data, pathField) {
const result = []
data.forEach((item) => {
const loop = (data, parent) => {
let temp = { ...data }
if (pathField) {
!temp.path && (temp.path = [])
temp.path = [...(parent?.path || []), temp[pathField]]
}
result.push(temp)
const child = data.children
if (child) {
for (let i = 0; i < child.length; i++) {
loop(child[i], data)
}
}
}
loop(item, null)
})
return result
}
/**
* 10位时间戳转换
* @param time
* @returns {string}
*/
export function tenBitTimestamp(time) {
const date = new Date(time * 1000)
const y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? '' + m : m
let d = date.getDate()
d = d < 10 ? '' + d : d
let h = date.getHours()
h = h < 10 ? '0' + h : h
let minute = date.getMinutes()
let second = date.getSeconds()
minute = minute < 10 ? '0' + minute : minute
second = second < 10 ? '0' + second : second
return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}
/**
* 13位时间戳转换
* @param time
* @returns {string}
*/
export function thirteenBitTimestamp(time) {
const date = new Date(time / 1)
const y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? '' + m : m
let d = date.getDate()
d = d < 10 ? '' + d : d
let h = date.getHours()
h = h < 10 ? '0' + h : h
let minute = date.getMinutes()
let second = date.getSeconds()
minute = minute < 10 ? '0' + minute : minute
second = second < 10 ? '0' + second : second
return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}
/**
* 获取随机id
* @param length
* @returns {string}
*/
export function uuid(length = 32) {
const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
let str = ''
for (let i = 0; i < length; i++) {
str += num.charAt(Math.floor(Math.random() * num.length))
}
return str
}
/**
* m到n的随机数
* @param m
* @param n
* @returns {number}
*/
export function random(m, n) {
return Math.floor(Math.random() * (m - n) + n)
}
/**
* addEventListener
* @type {function(...[*]=)}
*/
export const on = (function () {
return function (element, event, handler, useCapture = false) {
if (element && event && handler) {
element.addEventListener(event, handler, useCapture)
}
}
})()
/**
* removeEventListener
* @type {function(...[*]=)}
*/
export const off = (function () {
return function (element, event, handler, useCapture = false) {
if (element && event) {
element.removeEventListener(event, handler, useCapture)
}
}
})()
/**
* 删除URL中指定search参数,会将参数值一起删除
* @param {string} url 地址字符串
* @param {array} aParam 要删除的参数key数组,如['name','age']
* @return {string} 返回新URL字符串
*/
export function ridUrlParam(url, aParam) {
aParam.forEach((item) => {
const fromindex = url.indexOf(`${item}=`) //必须加=号,避免参数值中包含item字符串
if (fromindex !== -1) {
// 通过url特殊符号,计算出=号后面的的字符数,用于生成replace正则
const startIndex = url.indexOf('=', fromindex)
const endIndex = url.indexOf('&', fromindex)
const hashIndex = url.indexOf('#', fromindex)
let reg
if (endIndex !== -1) {
// 后面还有search参数的情况
const num = endIndex - startIndex
reg = new RegExp(`${item}=.{${num}}`)
url = url.replace(reg, '')
} else if (hashIndex !== -1) {
// 有hash参数的情况
const num = hashIndex - startIndex - 1
reg = new RegExp(`&?${item}=.{${num}}`)
url = url.replace(reg, '')
} else {
// search参数在最后或只有一个参数的情况
reg = new RegExp(`&?${item}=.+`)
url = url.replace(reg, '')
}
}
})
const noSearchParam = url.indexOf('=')
if (noSearchParam === -1) {
url = url.replace(/\?/, '') // 如果已经没有参数,删除?号
}
return url
}
/**
*
*获取value的类型
* @export
* @param {*} value
* @return {*} {String}
*/
export function getType(value) {
const type = Object.prototype.toString.call(value)
return type.match(/\[object (.*)\]/)[1].toLowerCase()
}
/**
*
*是否无效值
* @param {*} value
*/
export const isVoid = (value) =>
value === undefined || value === null || value === ''
/**
*
*去除对象中的无效值
* @param {*} object
* @return {*}
*/
export const validObject = (object) => {
if (!object) {
return {}
}
const result = { ...object }
Object.keys(result).forEach((key) => {
const value = result[key]
if (isVoid(value)) {
delete result[key]
}
})
return result
}
export const encryptWithRsa = (string) => {
let encrypt = new JSEncrypt()
let key = window.eipRSAPublicKey
if (!key) {
key =
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMnhQ99yP-eEU2jXdQWc6j-wWbqNLqOLinEGBY11WJUCmzHiEycDXPc6-3YMOvrdAiHZcjkMCzU_eRnBLUqkcNw9nhQrCak-sTpEVlAV21LskD6KMf-6PsfttUvpXeCO5g3Hg48F_vbLKxb8s_lcvQgCpKBIpsUdYRcp_PgSg8BQIDAQAB'
}
encrypt.setPublicKey(key)
return encrypt.encrypt(string)
}
export const isJSON = (str) => {
if (typeof str == 'string') {
try {
const obj = JSON.parse(str)
if (typeof obj == 'object' && obj) {
return true
} else {
return false
}
} catch (e) {
return false
}
}
}
/**
* 是否
* @param str
* @returns {boolean}
*/
export const isJsonStr = (str) => {
if (str && typeof str == 'string') {
try {
JSON.parse(str)
return true;
} catch (e) {
return false
}
return false;
}
}