-
Notifications
You must be signed in to change notification settings - Fork 3
/
tars-utils.js
1671 lines (1448 loc) · 43.8 KB
/
tars-utils.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* tars-utils
* https://github.com/Jamie-Yang/tars-utils.git
* version 1.0.1
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.tars = {}));
}(this, (function (exports) { 'use strict';
/**
* 数组切片
*
* @param {Array} arr 数组
* @param {number} size 切片长度
* @returns {Array} 切片后的二维数组
* @example
* chunk([1, 2, 3, 4], 2) => [[1, 2], [3, 4]]
*/
function chunk(arr) {
var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
return Array.from({
length: Math.ceil(arr.length / size)
}, function (_v, i) {
return arr.slice(i * size, i * size + size);
});
}
/**
* Polyfill for requestAnimationFrame
*
* @see https://github.com/darius/requestAnimationFrame/blob/master/requestAnimationFrame.js
*/
var lastTime = 0;
/**
* 回退方法
*
* @param {Function} callback 回调方法
* @returns {Function} fallback
*/
function fallback(callback) {
var now = Date.now();
var nextTime = Math.max(lastTime + 16, now);
return setTimeout(function () {
callback(lastTime = nextTime);
}, nextTime - now);
}
/**
* @param {Function} callback 回调方法
* @returns {Function} requestAnimationFrame 或 回退方法setTimeout
*/
function requestAnimFrame(callback) {
return (window.requestAnimationFrame || window.webkitRequestAnimationFrame || fallback)(callback);
}
/**
* @param {number} id 事件ID
* @returns {undefined}
*/
function cancelAnimFrame(id) {
(window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.clearTimeout)(id);
}
/**
* 获取UA
*
* @param {any} lower 是否转小写
* @returns {string} UA
*/
function ua (lower) {
return lower ? window.navigator.userAgent.toLowerCase() : window.navigator.userAgent;
}
/**
* 是否为Android系统
*
* @returns {boolean} 是否为Android系统
*/
function isAndroid() {
return /Android/i.test(ua());
}
/**
* 是否为iOS系统
*
* @returns {boolean} 是否为iOS系统
*/
function isIOS() {
return /iPhone|iPad|iPod/.test(ua());
}
/**
* 是否为iPad设备
*
* @returns {boolean} 是否为iPad设备
*/
function isIPad() {
return /iPad/.test(ua());
}
/**
* 是否为iPhone设备
*
* @returns {boolean} 是否为iPhone设备
*/
function isIPhone() {
return /iPhone/.test(ua());
}
/**
* 是否为iPhone刘海屏机型:X XS, XS Max, XR, 11, 11 Pro, 11 Pro Max
*
* @returns {boolean} 是否为微信客户端
*/
function isNotchIPhone() {
if (!isIPhone()) {
return false;
}
var screens = [{
dpr: 3,
width: 375,
height: 812
}, {
dpr: 3,
width: 414,
height: 896
}, {
dpr: 2,
width: 414,
height: 896
}];
if (typeof window !== 'undefined' && window) {
var _window = window,
devicePixelRatio = _window.devicePixelRatio,
screen = _window.screen;
var width = screen.width,
height = screen.height;
return screens.some(function (item) {
return item.dpr === devicePixelRatio && item.width === width && item.height === height;
});
}
return false;
}
/**
* 是否为微信客户端
*
* @returns {boolean} 是否为微信客户端
*/
function isWeixin() {
return /MicroMessenger/i.test(ua());
}
var root = document.documentElement;
var body = document.body;
/**
* 获取页面高度
*
* @returns {number} 页面高度
*/
function getPageHeight() {
return Math.max(root.scrollHeight, body.scrollHeight, root.clientHeight);
}
var root$1 = document.documentElement;
var body$1 = document.body;
/**
* 获取页面宽度
*
* @returns {number} 页面宽度
*/
function getPageWidth() {
return Math.max(root$1.scrollWidth, body$1.scrollWidth, root$1.clientWidth);
}
var root$2 = document.documentElement;
var body$2 = document.body;
/**
* 获取页面scrollTop
*
* @returns {number} 滚动值
*/
function getPageScrollTop() {
return root$2.scrollTop || body$2.scrollTop;
}
/**
* 获取元素样式
*
* @param {Element} el 元素
* @param {string} ruleName 属性名
* @returns {string} 样式
*/
function getStyle(el, ruleName) {
return getComputedStyle(el)[ruleName];
}
var root$3 = document.documentElement;
/**
* 获取视窗高度
*
* @returns {number} 视窗高度
*/
function getViewHeight() {
return root$3.clientHeight;
}
var root$4 = document.documentElement;
/**
* 获取视窗宽度
*
* @returns {number} 视窗宽度
*/
function getViewWidth() {
return root$4.clientWidth;
}
/**
* 判断元素是否在可视窗口可见
*
* @param {Element} el 元素
* @param {boolean} partiallyVisible 是否部分可见
* @returns {boolean} 是否可见
*/
function elementIsVisibleInViewport(el) {
var partiallyVisible = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var _el$getBoundingClient = el.getBoundingClientRect(),
top = _el$getBoundingClient.top,
left = _el$getBoundingClient.left,
bottom = _el$getBoundingClient.bottom,
right = _el$getBoundingClient.right;
var _window = window,
innerHeight = _window.innerHeight,
innerWidth = _window.innerWidth;
return partiallyVisible ? (top > 0 && top < innerHeight || bottom > 0 && bottom < innerHeight) && (left > 0 && left < innerWidth || right > 0 && right < innerWidth) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}
/**
* 消除非交互元素的touch事件
*/
function lockTouch() {
document.addEventListener('touchmove', function (e) {
e.preventDefault();
});
document.addEventListener('touchstart', preventDefault);
document.addEventListener('touchend', preventDefault);
/**
* 判断事件是否非由某类元素触发
*
* @param {Event} e 事件
* @param {string} tag 标签名
* @returns {boolean} 非指定元素
*/
function not(e, tag) {
return e.target.tagName !== tag.toUpperCase() && e.target.tagName !== tag.toLowerCase();
}
/**
* 阻止非交互元素触发事件
*
* @param {Event} e 事件
* @returns {undefined}
*/
function preventDefault(e) {
if (not(e, 'input') && not(e, 'textarea') && not(e, 'select') && not(e, 'menus')) e.preventDefault();
}
}
/**
* 生成随机Hex颜色值
*
* @returns {string} 随机Hex颜色值
*/
function randomColor() {
return '#' + ('00000' + (~~(Math.random() * (1 << 24))).toString(16)).slice(-6);
}
/**
* 框出所有元素,检测布局
*/
function outlineElements() {
document.querySelectorAll('*').forEach(function (el) {
el.style.outline = '1px solid ' + randomColor;
});
}
/**
* 将输入框光标定位在文端结尾处
*
* @param {Element} el 元素
*/
function putCursorAtEnd(el) {
el.focus(); // If this function exists... (IE 9+)
if (el.setSelectionRange) {
// Double the length because Opera is inconsistent about whether a carriage return is one character or two.
var len = el.value.length * 2; // Timeout seems to be required for Blink
setTimeout(function () {
el.setSelectionRange(len, len);
}, 0);
} else {
// As a fallback, replace the contents with itself
el.value = el.value; // eslint-disable-line no-self-assign
} // Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Chrome)
el.scrollTop = 999999;
}
/**
* 平滑滚动
*
* @param {object} options 配置项
* @param {Element|Window} [options.el] 滚动容器元素或window
* @param {number} [options.from] 起始位置
* @param {number} options.to 终止位置
* @param {number} [options.duration] 过渡时间
* @param {Function} [options.onEnd] 结束回调
*/
function scrollTo(options) {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = window.webkitRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
}
var _options$el = options.el,
el = _options$el === void 0 ? window : _options$el,
_options$from = options.from,
from = _options$from === void 0 ? 0 : _options$from,
to = options.to,
_options$duration = options.duration,
duration = _options$duration === void 0 ? 500 : _options$duration,
onEnd = options.onEnd;
var difference = Math.abs(from - to);
var step = Math.ceil(difference / duration * 50);
var scroll = function scroll(start, end, step) {
if (start === end) {
onEnd && onEnd();
return;
}
var d = start + step > end ? end : start + step;
if (start > end) {
d = start - step < end ? end : start - step;
}
if (el === window) {
window.scrollTo(0, d);
} else {
el.scrollTop = d;
}
window.requestAnimationFrame(function () {
return scroll(d, end, step);
});
};
scroll(from, to, step);
}
/**
* 设置元素样式
*
* @param {Element} el 元素
* @param {string} ruleName 样式名
* @param {string} val 样式
*/
function setStyle(el, ruleName, val) {
el.style[ruleName] = val;
}
/**
* 金额格式化,保留两位小数、千分位格式化 2333 -> 2,333.00
*
* @param {number} amount 金额
* @returns {string} 格式化结果
*/
function formatAmount(amount) {
var num = Number(amount);
if (isNaN(num)) {
return amount;
}
return num.toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}
/**
* 银行卡格式化,格式为四位分割
*
* @param {string|number} bankCard 银行卡号
* @param {string} separator 分隔符,默认空格
* @returns {string} 格式化结果
*/
function formatBankCard(bankCard) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' ';
var str = bankCard.toString().replace(/\s/g, '');
return str.replace(/(\d{4})(?=\d)/g, "$1".concat(separator));
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
/**
* 时间格式标记替换通用逻辑
*
* @param {object} time 时间对象:形式如defaults
* @param {string} format 格式描述:YYYY-MM-DD HH:mm:ss.SSS 或 d天 HH:mm:ss.SSS
* @returns {string} 2020-01-01 12:00:00.000 或 1天 12:00:00.00
*/
function formatTime() {
var time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var format = arguments.length > 1 ? arguments[1] : undefined;
var defaults = {
year: 0,
month: 0,
date: 0,
day: 0,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
};
var t = _objectSpread2(_objectSpread2({}, defaults), time);
var map = {
'Y+': t.year,
'M+': t.month,
'D+': t.date,
'H+': t.hour,
'm+': t.minute,
's+': t.second,
'S+': t.millisecond,
d: t.day
};
var result = format;
for (var k in map) {
if (new RegExp("(".concat(k, ")")).test(format)) {
var v = void 0;
if (k === 'd') {
v = map[k];
} else {
v = ('00' + map[k]).slice(-RegExp.$1.length);
}
result = result.replace(RegExp.$1, v);
}
}
return result;
}
/**
* 时间格式化
*
* @param {Date} date 时间对象
* @param {string} format 格式描述:YYYY-MM-DD HH:mm:ss.SSS
* @returns {string} 格式化结果:2020-01-01 12:00:00.000
*/
function formatDate(date, format) {
var time = {
year: date.getFullYear(),
month: date.getMonth() + 1,
date: date.getDate(),
hour: date.getHours(),
minute: date.getMinutes(),
second: date.getSeconds(),
millisecond: date.getMilliseconds()
};
return formatTime(time, format);
}
/**
* 剩余时间格式化(不支持年月,因其周期不固定)
*
* @param {number} remain 剩余毫秒数
* @param {string} format 格式描述:d天 HH:mm:ss.SSS
* @returns {string} 格式化结果:1天 12:00:00.00
*/
function formatRemainTime(remain, format) {
var SECOND = 1000;
var MINUTE = 60 * SECOND;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var time = {
day: Math.floor(remain / DAY),
hour: Math.floor(remain % DAY / HOUR),
minute: Math.floor(remain % HOUR / MINUTE),
second: Math.floor(remain % MINUTE / SECOND),
millisecond: Math.floor(remain % SECOND)
};
return formatTime(time, format);
}
/**
* 手机号格式化,格式为344
*
* @param {string|number} tel 手机号码
* @param {string} separator 分隔符,默认空格
* @returns {string} 格式化结果
*/
function formatTel(tel) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' ';
var str = tel.toString().replace(/\s/g, '');
if (/(\d{3})(\d{4})(\d{4})/.test(str)) {
return "".concat(RegExp.$1).concat(separator).concat(RegExp.$2).concat(separator).concat(RegExp.$3);
}
return tel;
}
/**
* 函数组合
* 可将 fn1(fn2(fn3(fn4(x)))) 这种嵌套的调用方式
* 改成 compose(fn1,fn2,fn3,fn4)(x) 的方式调用
*
* @param {...Function} funcs 方法
* @returns {Function} 组合结果方法
*/
function compose() {
for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
if (funcs.length === 0) {
return function (arg) {
return arg;
};
}
if (funcs.length === 1) {
return funcs[0];
}
return funcs.reduce(function (a, b) {
return function () {
return a(b.apply(void 0, arguments));
};
});
}
/**
* 获取数据类型
*
* @param {*} val 数据
* @returns {string} 类型名 object,array,string,boolean,number,map,set,function, undefined
*/
function getType(val) {
return Object.prototype.toString.call(val).slice(8, -1) // [object XXX]
.toLowerCase();
}
/**
* 检查数据类型是否为:对象
*
* @param {*} obj 数据
* @returns {boolean} 是否
*/
function isObject(obj) {
return getType(obj) === 'object';
}
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs;
var lastThis;
var maxWait;
var result;
var timerId;
var lastCallTime;
var lastInvokeTime = 0;
var leading = false;
var maxing = false;
var trailing = true;
if (typeof func !== 'function') {
throw new TypeError('Expected a function');
}
wait = Number(wait) || 0; // eslint-disable-line no-param-reassign
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? Math.max(Number(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
/**
* @param {number} time 时间戳
* @returns {*} 方法执行结果
*/
function invokeFunc(time) {
var args = lastArgs;
var thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
/**
* @param {number} time 时间戳
* @returns {*} 方法执行结果
*/
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time; // Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait); // Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
/**
* @param {number} time 时间戳
* @returns {number} 剩余等待时间
*/
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime;
var timeSinceLastInvoke = time - lastInvokeTime;
var timeWaiting = wait - timeSinceLastCall;
return maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
/**
* @param {number} time 时间戳
* @returns {boolean} 可否调用
*/
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime;
var timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
/**
* @returns {number} 定时器ID
*/
function timerExpired() {
var time = Date.now();
if (shouldInvoke(time)) {
return trailingEdge(time);
} // Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
/**
* @param {number} time 时间戳
* @returns {*} 方法执行结果
*/
function trailingEdge(time) {
timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
/**
* 取消方法
*/
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
/**
* 立即执行
*
* @returns {*} 方法执行结果
*/
function flush() {
return timerId === undefined ? result : trailingEdge(Date.now());
}
/**
* @param {...*} args 方法参数
* @returns {*} 方法执行结果
*/
function debounced() {
var time = Date.now();
var isInvoking = shouldInvoke(time);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
lastArgs = args;
lastThis = this; // eslint-disable-line no-invalid-this
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @since 0.1.0
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true;
var trailing = true;
if (typeof func !== 'function') {
throw new TypeError('Expected a function');
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
leading: leading,
maxWait: wait,
trailing: trailing
});
}
/**
* 优化图片尺寸和文件大小
* 不支持Gif格式
*
* @param {object|string} image 原始图片,支持File对象和base64字符串
* @param {number} [quality] 品质,范围为 0 - 1, 仅支持MIME类型为 image/jpeg 或 image/webp
* @param {object} [options={}] 配置项
* @param {number} [options.maxWidth=750] 生成图片的最大宽度,若原始图片宽度小于此值,则使用原始图片的宽度
* @param {string} [options.mimeType] 生成图片的MIME类型
* @returns {Promise<Blob>} 生成图片 Blob对象
*/
function optimizeImage(image) {
var quality = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.9;
var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
_ref$maxWidth = _ref.maxWidth,
maxWidth = _ref$maxWidth === void 0 ? 750 : _ref$maxWidth,
mimeType = _ref.mimeType;
return new Promise(function (resolve, reject) {
if (image instanceof File) {
var reader = new FileReader();
reader.onload = function () {
toBlob(this.result);
};
reader.readAsDataURL(image);
} else if (typeof image === 'string') {
toBlob(image);
}
/**
* To Blob
*
* @param {string} data - Image: Data URL
* @returns {Promise<Blob>} 生成图片 Blob对象
*/
function toBlob(data) {
var type = data.match(/data:([^;,]+)/);
if (Array.isArray(type)) {
var outputType = mimeType ? mimeType : type[1];
if (outputType === 'image/gif') {
return resolve(image);
}
var virtualImage = new Image();
virtualImage.src = data;
virtualImage.onload = function () {
var width = this.naturalWidth;
var height = this.naturalHeight;
if (width > maxWidth) {
height = Math.round(maxWidth * height / width);
width = maxWidth;
}
var canvas = document.createElement('canvas');
canvas.width = width;