-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
426 lines (374 loc) · 11 KB
/
index.js
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/**
* @RegExp
* @desc Common RegExp
*/
export const URL_REG = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const PHONE_REG = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
/**
* @utils
* @desc types check
*/
export const isString = function (str) {
return typeof str === 'string'
}
export const isNumber = function (str) {
return typeof str === 'number'
}
export const isBoolean = function (str) {
return typeof str === 'boolean'
}
export const isFunction = function (fn) {
return typeof fn === 'function'
}
export const isObject = function (obj) {
return obj && typeof obj === 'object'
}
export const isEmptyObject = function (obj) {
return isObject(obj) && Object.keys(obj).length
}
export const isUndefined = function (any) {
return typeof any === undefined || any === undefined
}
export const isArray = function (arr) {
return Array.isArray(arr) || Object.prototype.toString.call(arr) === '[object Array]'
}
export const isArrayLike = function (obj) {
let length = !!obj && "length" in obj && obj.length
return isArray(obj) || length === 0 ||
typeof length === 'number' && length > 0 && (length - 1) in obj
}
export const isUrl = function (str) {
return URL_REG.test(str);
}
export const isPhoneNumber = function (str) {
return PHONE_REG.test(str);
}
/**
* @author Vuchan
* @desc same implementation like follow link, but more simpler
* https://www.npmjs.com/package/is-plain-object
*/
export const isPlainObject = function (obj) {
return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;
}
/**
* @utils
* @desc helpers
*/
/**
* hasProp
* @desc 检测对象是否存在改属性
* @param {Object} obj
* @param {String} key
* @param {Boolean} own
* @returns {Boolean}
*/
export const hasProp = function (obj, key, own) {
return isObject(obj) && own ? obj.hasOwnProperty(key) : !isUndefined(obj[key])
}
/**
* when
* @desc when `fulfilled` so do the next by `then`
* @param {any*} value
* @param {Function} fulfilled
* @param {Function} rejected
*/
export const when = function (value, fulfilled, rejected) {
var promise = Promise.resolve(value);
if (arguments.length < 2) {
return promise;
}
return promise.then(fulfilled, rejected);
}
/**
* inArray
* @desc To check one `item` in an `array` or not
* @param {Array} array
* @param {any*} item
*/
export const inArray = function (array, item) {
return isArray(array) ? array.includes && array.includes(item) || ~array.indexOf(item) : null
}
/**
* toArray
* @desc Make the `arguments` to be an real array
*/
export const toArray = function () {
return [].slice.call(arguments)
}
/**
* capitalize
* @param {String} str
*/
export function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
* before 将函数合并执行,beforeFn先执行,originalFn后执行
* @author Vuchan
* @param {*} beforeFn 先执行执行的函数
* @param {*} originalFn 原函数
* @param {*} context 上下文this
* @return any*
*/
export const before = function (originalFn, beforeFn, context) {
return function () {
if (beforeFn.apply(context, arguments) === false) return false
return originalFn.apply(context, arguments)
}
}
/**
* after 将函数合并执行,originalFn先执行,afterFn后执行
* @author Vuchan
* @param {*} originalFn 原函数
* @param {*} afterFn 之后执行的函数
* @param {*} context 上下文this
* @return any*
*/
export const after = function(originalFn, afterFn, context) {
return function () {
let ret = originalFn.apply(context, arguments)
if (ret === false) return false
return afterFn.apply(context, arguments)
}
}
/**
* @desc 生成指定范围内随机数 int/float [start, end]
* @author Vuchan
* @param {Number} start
* @param {Number} end
* @param {Boolean|Number} len len == 0 => int | len === N => 带 N 位的小数点,若小数点位数大于随机数,则返回当前长度下最大的完整随机数
* @return {Number}
*/
export const random = (start, end, len = 0) => {
if (start !== undefined && typeof +start === 'number') {
const val = end !== undefined && typeof +end === 'number'
? Math.random() * (end - start + 1) + start
: Math.random() * start + 1;
let [int, double] = `${val}`.split('.')
if (isNumber(len)) {
if (len) {
return +(int + '.' +`${double}`.substr(0, len))
}
}
return +int || parseInt(val, 10)
}
}
// historical reason
export const geneRandomNum = random;
/**
* delay 基于Promise的延时调用
* @author VuChan
* @param {Function|Object|Number} fnOrObj
* @param {Number} ms=1000
* @return {Promise}
*/
export function delay(fnOrObj = 1000, ms = 1000) {
if (typeof fnOrObj === 'number') {
ms = fnOrObj;
fnOrObj = null;
}
return new Promise((resolve) => {
const timerId = setTimeout(() => {
clearTimeout(timerId);
return resolve(typeof fnOrObj === 'function' ? fnOrObj() : fnOrObj);
}, ms);
});
}
/**
* getMaxValIgnoreSign
* @author Vuchan
* @desc 返回所有数中绝对值最大的数(忽略符号)
* @param {Number} args
* @return {Number}
* @example
* getMaxAbsOriVal(-10, 11, -12, 9) // -12
* getMaxAbsOriVal(-10.13, 10.12) // -10.13
*/
export const getMaxValIgnoreSign = (...args) => {
return args.find(t => Math.abs(t) === args.map(t => Math.abs(+t) || 0).sort((a, b) => b - a)[ 0 ] && t);
}
/**
* getRightEnv
* @author Vuchan
* @desc 取得当前正确的运行环境 ['test', 'dev', 'prod' = '']
* @return {String}
*/
export const getRightEnv = function () {
const host = window.location.host;
if (/^test.*\.ff\.cn/.test(host)) {
return 'test';
}
if (/^dev.*\.ff\.cn/.test(host)) {
return 'dev';
}
return '';
}
/**
* classNames
* @author Vuchan
* @desc Combine all arguments to be a classList String.
* @param {Object} any*
* @example
* classNames({ a: 1, b: 0, c: 'c' })
* // "a c"
* classNames('a', 'b', 'c', { d: 1, e: 0 })
* // "a b c d"
* classNames('a', 'b', 'c', { d: 1, e: 0 }, {f: 'e'})
* // "a b c d f"
* classNames('a', 'b', 'c', { d: 1, e: 0 }, {f: 'e'}, ['g', 'h', {'i': '1', 'j': false }])
* // "a b c d f g h i"
*
* @return {String} classnames string
*/
export const classNames = (...args) => {
return args.map(t => {
if (Array.isArray(t)) {
return t.map(i => classNames(i)).join(' ')
} else if (typeof t === 'object') {
return Object.keys(t).filter(k => t[k]).join(' ')
} else {
return typeof t !== 'string' ? t.toString() : t
}
}).join(' ')
}
/**
* loadScript
* @author Vuchan
* @desc lazy load script form a url
* @param {String} url
* @return {Promise}
*/
export const loadScript = function(url) {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.body.appendChild(script);
return new Promise((resolve) => {
if (script.readyState) { // IE
script.onreadystatechange = function change() {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
resolve();
}
};
} else { // Others
script.onload = function load() {
resolve();
};
}
});
}
/**
* checkPropsValue
* @desc 检查传入对象的属性值,抛出传入的msg或内部默认的错误
* @author Vuchan
* @param {Object} obj
* @param {String} msg
* @throws Error
* @return {Boolean}
*/
export const checkPropsValue = (obj, msg) => {
return Object.keys(obj).reduce((status, key) => {
if (!obj[key] && obj[key] !== 0) {
const error = new Error(msg || `${key}'s value is required but it's ${obj[key]}!`);
error.errorKey = key;
throw error;
} else {
return status = true;
}
}, true);
};
/**
* getQueryString
* @author VuChan
* @desc 生成链接后面选项参数
* @param {String} url
* @param {Object} Options
* @return {Object | null}
* @design 穷举法:
* 0. a.com? | a.com?& | a.com?&=&1=2&&
* 1. a.com?a=1&b=2&c=&d=3
* 2. a.com?a=1&b=2&c=&d=3/#/hash
* 3. a.com/#/hash?a=1&b=2&c=&d=3
* 4. http://mcar.ff.cn/uploading.html/#/?shopId=5&orderId=231&loanOrderId=59&orderAmount=64900.00&period=36&downPayRate=0.1
* 5. http://mcar.ff.cn/uploading.html?shopId=5&orderId=231&loanOrderId=59&orderAmount=64900.00&period=36&downPayRate=0.1/#/
* 6. http://devwc.ff.cn/BindingMobileNumber.html?redirect_url=http%3A%2F%2Fdevwc.ff.cn%2Factivity%2Fshake.html%3FmktId%3D201805070000008%26subType%3D103
* @requires
* 1. 减去 hash 符号提取正常的 url
* 2. 仅提取正确queryString
* 3. 如果是 number 则需要转化成 number
* @example
* getQueryString(location.href)
*/
export const getQueryString = (
url = window.location.href,
options = {
cutHash: true, // replace hash `/#/{path}` to be ''
decoder: decodeURIComponent, // self decoder or browser's
decodeEach: false,
all: true, // need all value whatever it is valid or not
encode: false, // if u need? `false | encodeURLComponent | function`
placeholder: '', // if value is invalid, so puts the `placeholder`
},
) => {
const defaultOptions = {
cutHash: true, // replace hash `/#/{path}` to be ''
decoder: decodeURIComponent, // self decoder or browser's
decodeEach: false,
all: true, // need all value whatever it is valid or not
encode: false, // if u need? `false | encodeURLComponent | function`
placeholder: '', // if value is invalid, so puts the `placeholder`
};
options = { ...defaultOptions, ...options };
const parse = str => {
if (!str || !str.trim().length) return null;
else {
if (
!~str.indexOf('?') &&
(~str.indexOf('=') &&
~str.indexOf('&'))
) {
str = str.split('&').map(t => t.trim()).filter(t => ~t.indexOf('=')).map(t => (options.decodeEach ? options.decoder(t) : t));
} else {
str = [str];
}
if (str.length) {
return str.reduce((r, c) => {
c = c.split('=');
if (c.length > 2) c = [c.shift(), c.join('=')];
if (c[0]) {
if (c[1]) {
r[c[0]] = +c[1] ? +c[1] : c[1];
} else {
r[c[0]] = options.placeholder;
}
}
return r;
}, {});
} else {
return null;
}
}
};
let str = !options.decodeEach && typeof options.decoder === 'function' ? options.decoder(url) : url;
// type check of str value
if (!str || typeof str !== 'string' || !str.trim()) return null;
if (options.cutHash) {
// match this format like -> /#/ | /#/{word}
str = str.replace(/\/?\#\/(\w*\b)?/, '');
}
if (~str.indexOf('?')) {
// splits `?` only once
str = str.split('?');
if (str.length > 2) {
str = [str.shift(), str.join('?')];
}
str = str[1];
} else {
// if no any `?` sign returns null
return null
}
return parse(str);
};
// historical reason
export const getSearchParams = getQueryString;