-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
2725 lines (1393 loc) · 160 KB
/
index.html
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
<!DOCTYPE html>
<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/sh-article/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="/sh-article/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/sh-article/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="apple-touch-icon" sizes="180x180" href="/sh-article/images/apple-touch-icon-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="32x32" href="/sh-article/images/favicon-32x32-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="16x16" href="/sh-article/images/favicon-16x16-next.png?v=5.1.4">
<link rel="mask-icon" href="/sh-article/images/logo.svg?v=5.1.4" color="#222">
<meta name="keywords" content="Hexo, NexT" />
<meta name="description" content="灵活跳跃诈笑看天下 乐似仙">
<meta property="og:type" content="website">
<meta property="og:title" content="SZU_SH">
<meta property="og:url" content="http://yoursite.com/index.html">
<meta property="og:site_name" content="SZU_SH">
<meta property="og:description" content="灵活跳跃诈笑看天下 乐似仙">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SZU_SH">
<meta name="twitter:description" content="灵活跳跃诈笑看天下 乐似仙">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/sh-article/',
scheme: 'Gemini',
version: '5.1.4',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
fancybox: true,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
duoshuo: {
userId: '0',
author: '博主'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="http://yoursite.com/"/>
<title>SZU_SH</title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container sidebar-position-left
page-home">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/sh-article/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">SZU_SH</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle"></p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/sh-article/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/sh-article/categories/" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br />
分类
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/sh-article/archives/" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
归档
</a>
</li>
<li class="menu-item menu-item-search">
<a href="javascript:;" class="popup-trigger">
<i class="menu-item-icon fa fa-search fa-fw"></i> <br />
搜索
</a>
</li>
</ul>
<div class="site-search">
<div class="popup search-popup local-search-popup">
<div class="local-search-header clearfix">
<span class="search-icon">
<i class="fa fa-search"></i>
</span>
<span class="popup-btn-close">
<i class="fa fa-times-circle"></i>
</span>
<div class="local-search-input-wrapper">
<input autocomplete="off"
placeholder="搜索..." spellcheck="false"
type="text" id="local-search-input">
</div>
</div>
<div id="local-search-result"></div>
</div>
</div>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<section id="posts" class="posts-expand">
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/sh-article/2021/07/03/常用的函数工具函数/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="$SH">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars1.githubusercontent.com/u/17661313?s=460&v=4">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="SZU_SH">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/sh-article/2021/07/03/常用的函数工具函数/" itemprop="url">常用的函数工具函数</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2021-07-03T10:27:55+08:00">
2021-07-03
</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/sh-article/categories/JS/" itemprop="url" rel="index">
<span itemprop="name">JS</span>
</a>
</span>
</span>
<span id="/sh-article/2021/07/03/常用的函数工具函数/" class="leancloud_visitors" data-flag-title="常用的函数工具函数">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数:</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>函数式是一种很好用的编程方式,使用函数式编程一开始可能还不是很习惯,但在你习惯之后会发现这能帮你编写出简洁且充满表达能力的代码。下面介绍一下,日常开发中运用函数式的一些技巧以及函数式的原理。</p>
<h2 id="compose"><a href="#compose" class="headerlink" title="compose"></a>compose</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">compose(...fns)</span><br></pre></td></tr></table></figure>
<p>compose基本是大部分函数式都会用到的函数,他的作用是把传入的方法从右往左,把前一个的返回值返回给下一个,redux的中间件就是基于compose实现的。</p>
<h3 id="源码"><a href="#源码" class="headerlink" title="源码"></a>源码</h3><p>compose 的源码也比较简单,但是思维方式可能会比较绕。简单来说就是通过reduce让函数一层一层嵌套,传进的函数会嵌套在最里面,所以会最先执行。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compose</span>(<span class="params">...fns</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (fns.length === <span class="number">0</span>) <span class="keyword">return</span> <span class="function"><span class="params">args</span> =></span> args;</span><br><span class="line"> <span class="keyword">if</span> (fns.length === <span class="number">1</span>) <span class="keyword">return</span> fns[<span class="number">0</span>];</span><br><span class="line"> <span class="keyword">return</span> fns.reduce(<span class="function">(<span class="params">f,g</span>) =></span> (...args) => f(g(...args)))</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<p>常见的用法,除了有reduce这种中间件的用法外,还可以是比方说我们有几个步骤,每个步骤需要把上一个步骤的值传进来,我们就可以利用compose来简化我们的写法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">compose(</span><br><span class="line"> step3,</span><br><span class="line"> step2,</span><br><span class="line"> step1,</span><br><span class="line">)(<span class="string">'begin'</span>)</span><br></pre></td></tr></table></figure>
<h2 id="cancellable"><a href="#cancellable" class="headerlink" title="cancellable"></a>cancellable</h2><p>开发中可能会碰到这样的需求,需要让一些函数变成可取消的。这部分的逻辑其实是可以复用的。下面看看可以如何去实现这样一个功能。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 首先我们可以实现一个类似axios里的CancelToken</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createCancelToken</span>(<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">let</span> cancel;</span><br><span class="line"> <span class="keyword">const</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">_, reject</span>) =></span> {</span><br><span class="line"> cancel = reject;</span><br><span class="line"> });</span><br><span class="line"> <span class="keyword">return</span> {</span><br><span class="line"> promise,</span><br><span class="line"> cancel</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">cancellable</span>(<span class="params">fn, cancelPromise</span>) </span>{</span><br><span class="line"> <span class="keyword">return</span> <span class="function">(<span class="params">...args</span>) =></span> {</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">Promise</span>.race([fn.apply(<span class="literal">null</span>, ...args), cancelPromise]) </span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">request</span>(<span class="params"></span>) </span>{}</span><br><span class="line"><span class="keyword">const</span> cancelToken = createCancelToken();</span><br><span class="line"><span class="keyword">const</span> cancellableRequest = cancellable(request, cancelToken.promise);</span><br><span class="line"></span><br><span class="line">cancellableRequest();</span><br><span class="line"><span class="comment">// 调用这个函数即可取消上面的cancellableRequest</span></span><br><span class="line">cancelToken.cancel();</span><br></pre></td></tr></table></figure>
<h2 id="concurrent"><a href="#concurrent" class="headerlink" title="concurrent"></a>concurrent</h2><p>用来控制函数并发量。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">concurrent</span>(<span class="params">count, fn</span>) </span>{</span><br><span class="line"> <span class="keyword">const</span> semaphore = <span class="keyword">new</span> Semaphore(count);</span><br><span class="line"> </span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">async</span> <span class="function"><span class="keyword">function</span> (<span class="params">...args</span>) </span>{</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">await</span> semaphore.acquire();</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">await</span> fn(...args);</span><br><span class="line"> } <span class="keyword">finally</span> {</span><br><span class="line"> semaphore.release();</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">request</span>(<span class="params"></span>) </span>{}</span><br><span class="line"><span class="comment">// 并发量只有1的</span></span><br><span class="line"><span class="keyword">const</span> concurrentRequest = concurrent(<span class="number">1</span>, request);</span><br><span class="line">concurrentRequest().then(<span class="function"><span class="params">()</span> =></span> {})</span><br><span class="line"><span class="comment">// 只有等上一个结束了这个函数才会执行</span></span><br><span class="line">concurrentRequest().then(<span class="function"><span class="params">()</span> =></span> {})</span><br></pre></td></tr></table></figure>
<h2 id="retryable"><a href="#retryable" class="headerlink" title="retryable"></a>retryable</h2><p>碰到错误就重试</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">retryable</span>(<span class="params">fn, times</span>) </span>{</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">async</span> (...args) => {</span><br><span class="line"> <span class="keyword">let</span> retryTimes = <span class="number">0</span>;</span><br><span class="line"> <span class="keyword">while</span> (<span class="literal">true</span>) {</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">const</span> res = <span class="keyword">await</span> fn(...args);</span><br><span class="line"> <span class="keyword">return</span> res;</span><br><span class="line"> } <span class="keyword">catch</span> (e) {</span><br><span class="line"> retryTimes++;</span><br><span class="line"> <span class="keyword">if</span> (retryTimes >= times) {</span><br><span class="line"> <span class="keyword">throw</span> e;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">request</span>(<span class="params"></span>)</span>{}</span><br><span class="line"><span class="keyword">const</span> retryableRequest = retryable(request, <span class="number">5</span>);</span><br><span class="line"><span class="comment">// 重试5次后任然失败则会抛出错误</span></span><br><span class="line">retryableRequest()</span><br></pre></td></tr></table></figure>
<h2 id="结合"><a href="#结合" class="headerlink" title="结合"></a>结合</h2><p>稍微改造一下,我们就可以通过compose来结合上面几个函数最终生成一个功能强大的request</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> cancellable = <span class="function">(<span class="params">cancelPromise</span>) =></span> (fn) => {</span><br><span class="line"> <span class="keyword">return</span> <span class="function">(<span class="params">...args</span>) =></span> {</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">Promise</span>.race([fn.apply(<span class="literal">null</span>, ...args), cancelPromise]) </span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> concurrent = <span class="function">(<span class="params">count</span>) =></span> (fn) => {</span><br><span class="line"> <span class="keyword">const</span> semaphore = <span class="keyword">new</span> Semaphore(count);</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">async</span> <span class="function"><span class="keyword">function</span> (<span class="params">...args</span>) </span>{</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">await</span> semaphore.acquire();</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">await</span> fn(...args);</span><br><span class="line"> } <span class="keyword">finally</span> {</span><br><span class="line"> semaphore.release();</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> retryable = <span class="function">(<span class="params">times</span>) =></span> (fn) => {</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">async</span> (...args) => {</span><br><span class="line"> <span class="keyword">let</span> retryTimes = <span class="number">0</span>;</span><br><span class="line"> <span class="keyword">while</span> (<span class="literal">true</span>) {</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">const</span> res = <span class="keyword">await</span> fn(...args);</span><br><span class="line"> <span class="keyword">return</span> res;</span><br><span class="line"> } <span class="keyword">catch</span> (e) {</span><br><span class="line"> retryTimes++;</span><br><span class="line"> <span class="keyword">if</span> (retryTimes >= times) {</span><br><span class="line"> <span class="keyword">throw</span> e;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"><span class="keyword">const</span> cancelToken = createCancelToken();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 这样我们就可以得到一个同时拥有这三个能力的request函数了</span></span><br><span class="line"><span class="keyword">const</span> strongRequest = compose(</span><br><span class="line"> cancellable(cancelToken.promise),</span><br><span class="line"> concurrent(<span class="number">2</span>),</span><br><span class="line"> retryable(<span class="number">5</span>),</span><br><span class="line">)(request)</span><br></pre></td></tr></table></figure>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/sh-article/2021/02/21/优雅的控制并发/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="$SH">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars1.githubusercontent.com/u/17661313?s=460&v=4">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="SZU_SH">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/sh-article/2021/02/21/优雅的控制并发/" itemprop="url">优雅的控制并发</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2021-02-21T09:07:00+08:00">
2021-02-21
</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/sh-article/categories/JS/" itemprop="url" rel="index">
<span itemprop="name">JS</span>
</a>
</span>
</span>
<span id="/sh-article/2021/02/21/优雅的控制并发/" class="leancloud_visitors" data-flag-title="优雅的控制并发">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数:</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>先面试或者实际开发的需求中,我们常常会碰到需要控制并发量的需求,那么如何才能优雅的去实现这个需求呢,下面简单介绍几种实现方式。</p>
<p>比方说我们有个需求是,需要去请求多个请求,但是并发的请求量不得超过5.</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">const</span> requests = [request1, request2, request3, request4,request5, request6, request7, request8];</span><br></pre></td></tr></table></figure>
<h2 id="方式一"><a href="#方式一" class="headerlink" title="方式一"></a>方式一</h2><p>简单通过分组来实现</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 切分数组</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">chunk</span>(<span class="params">array, size = <span class="number">1</span></span>) </span>{</span><br><span class="line"> size = <span class="built_in">Math</span>.max(<span class="built_in">Number</span>.parseInt(size), <span class="number">0</span>)</span><br><span class="line"> <span class="keyword">const</span> length = array == <span class="literal">null</span> ? <span class="number">0</span> : array.length</span><br><span class="line"> <span class="keyword">if</span> (!length || size < <span class="number">1</span>) {</span><br><span class="line"> <span class="keyword">return</span> []</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">let</span> index = <span class="number">0</span></span><br><span class="line"> <span class="keyword">let</span> resIndex = <span class="number">0</span></span><br><span class="line"> <span class="keyword">const</span> result = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="built_in">Math</span>.ceil(length / size))</span><br><span class="line"></span><br><span class="line"> <span class="keyword">while</span> (index < length) {</span><br><span class="line"> result[resIndex++] = slice(array, index, (index += size))</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> result</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">concurrentRequest</span>(<span class="params">requests, limit</span>) </span>{</span><br><span class="line"> <span class="keyword">const</span> chunks = chunk(requests, limit);</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < chunks.length; i++) {</span><br><span class="line"> <span class="keyword">const</span> chunk = chunks[i];</span><br><span class="line"> <span class="keyword">await</span> <span class="built_in">Promise</span>.all(chunk.map(<span class="function">(<span class="params">request</span>) =></span> request()));</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<p>但是这样有个问题,虽然限制了最大的并发量,但是每次得等每个分片的请求都结束了才能进入到下一个循环,这样就不能最大效率的利用并发量了。</p>
<h2 id="Semaphore"><a href="#Semaphore" class="headerlink" title="Semaphore"></a>Semaphore</h2><p>为了最大化的利用并发量,我们可以用一个叫做Semaphore的类,像java,c++,c#经常会使用它来实现并发量的控制</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Semaphore</span> </span>{</span><br><span class="line"> resolves = [];</span><br><span class="line"> limit = <span class="number">0</span>;</span><br><span class="line"> cur = <span class="number">0</span>;</span><br><span class="line"> <span class="keyword">constructor</span>(limit) {</span><br><span class="line"> <span class="keyword">this</span>.limit = limit;</span><br><span class="line"> }</span><br><span class="line"> </span><br><span class="line"> acquire() {</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =></span> {</span><br><span class="line"> <span class="keyword">this</span>.cur++;</span><br><span class="line"> <span class="keyword">if</span> (<span class="keyword">this</span>.cur < <span class="keyword">this</span>.limit) {</span><br><span class="line"> resolve();</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> <span class="keyword">this</span>.resolves.push(resolve);</span><br><span class="line"> }</span><br><span class="line"> });</span><br><span class="line"> }</span><br><span class="line"> </span><br><span class="line"> release() {</span><br><span class="line"> <span class="keyword">this</span>.cur --;</span><br><span class="line"> <span class="keyword">if</span> (<span class="keyword">this</span>.resolves.length > <span class="number">0</span>) {</span><br><span class="line"> <span class="keyword">this</span>.resolves.shift()();</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">concurrentRequest</span>(<span class="params">requests, limit</span>) </span>{</span><br><span class="line"> <span class="keyword">const</span> semaphore = <span class="keyword">new</span> Semaphore(limit);</span><br><span class="line"> <span class="keyword">await</span> <span class="built_in">Promise</span>.all(requests.map(<span class="keyword">async</span> (request) => {</span><br><span class="line"> <span class="keyword">await</span> semaphore.acquire();</span><br><span class="line"> <span class="keyword">await</span> request().finally(<span class="function"><span class="params">()</span> =></span> {</span><br><span class="line"> semaphore.release();</span><br><span class="line"> })</span><br><span class="line"> }))</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<p>这样相当于形成了一个并发池,先进入到池子里的方法会执行,当池子满了后,后面进入的方法,就会等待池子释放信号才能进入,先进入的方法在执行完后,调用 <code>semaphore.release</code> 通知池子有一个空位了,后面的方法通过 <code>await semaphore.acquire</code> 来接收这个信号并继续执行,我们可以看到这个用法的代码也是非常的简单直观,并且保证了并发量一直维持在这没有浪费</p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/sh-article/2020/05/18/ts高级用法/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="$SH">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars1.githubusercontent.com/u/17661313?s=460&v=4">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="SZU_SH">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/sh-article/2020/05/18/ts高级用法/" itemprop="url">ts高级用法</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2020-05-18T23:38:37+08:00">
2020-05-18
</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/sh-article/categories/ts/" itemprop="url" rel="index">
<span itemprop="name">ts</span>
</a>
</span>
</span>
<span id="/sh-article/2020/05/18/ts高级用法/" class="leancloud_visitors" data-flag-title="ts高级用法">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数:</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p><code>typescript</code> 的基本使用方式基本已经可以覆盖到我们绝大部门的使用场景,但是我们也任会碰到一些特殊的场景需要我们使用一些高级的ts的用法,下面总结一下我常用的一些用法。</p>
<h3 id="keyof"><a href="#keyof" class="headerlink" title="keyof"></a>keyof</h3><p><code>keyof</code> 能够帮助我们快速生成 <code>interface</code> 的 key 的类型。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">interface</span> A {</span><br><span class="line"> age: <span class="built_in">number</span>;</span><br><span class="line"> name: <span class="built_in">string</span>;</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> AKeys = keyof A; <span class="comment">// age | name</span></span><br></pre></td></tr></table></figure>
<h3 id="利用-keyof-提取接口"><a href="#利用-keyof-提取接口" class="headerlink" title="利用 keyof 提取接口"></a>利用 keyof 提取接口</h3><p>有时候我们可能会碰到需要提取接口部门结构的需求,这时候我们可以利用 ts 提供的<code>pick</code>类型</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">type</span> pick<T, K <span class="keyword">extends</span> keyof T> = {</span><br><span class="line"> [key <span class="keyword">in</span> K]: T[key]</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> A {</span><br><span class="line"> age: <span class="built_in">number</span>;</span><br><span class="line"> name: <span class="built_in">string</span>;</span><br><span class="line"> sex: <span class="built_in">string</span>;</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> C = pick<A, <span class="string">'age'</span> | <span class="string">'sex'</span>>; <span class="comment">// { age: number; sex: string; }</span></span><br></pre></td></tr></table></figure>
<h3 id="多态"><a href="#多态" class="headerlink" title="多态"></a>多态</h3><p>常用的使用场景就是我们可能需要根据传入值的类型来确定返回值的类型</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">interface</span> Create {</span><br><span class="line"> (val: <span class="built_in">number</span>): <span class="built_in">number</span></span><br><span class="line"> (val: <span class="built_in">string</span>): <span class="built_in">string</span></span><br><span class="line"> (val: <span class="built_in">Date</span>): <span class="built_in">Date</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<p>有个典型的例子就是eventBus,我们可能需要在不同的事件监听不同的类型的数据和广播不同类型的数据</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">enum</span> EventName {</span><br><span class="line"> sayName,</span><br><span class="line"> run,</span><br><span class="line">}</span><br><span class="line"><span class="keyword">interface</span> EventBusOn {</span><br><span class="line"> (event: EventName.sayName, cb: <span class="function">(<span class="params">params: {name: <span class="built_in">string</span>}</span>) =></span> <span class="built_in">void</span>): <span class="built_in">void</span></span><br><span class="line"> (event: EventName.run, cb: <span class="function">(<span class="params">params: {duration: <span class="built_in">number</span>}</span>) =></span> <span class="built_in">void</span>): <span class="built_in">void</span></span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> EventBusEmit {</span><br><span class="line"> (event: EventName.sayName, params: {name: <span class="built_in">string</span>}): <span class="built_in">void</span></span><br><span class="line"> (event: EventName.run, params: {duration: <span class="built_in">number</span>}): <span class="built_in">void</span></span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> EventBus {</span><br><span class="line"> on: EventBusOn;</span><br><span class="line"> emit: EventBusEmit;</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> eventBus: EventBus = <span class="keyword">new</span> Vue();</span><br><span class="line">eventBus.on(EventName.sayName, <span class="function">(<span class="params">{name}</span>) =></span> {</span><br><span class="line"> <span class="built_in">console</span>.log(name);</span><br><span class="line">});</span><br><span class="line">eventBus.emit(EventName.sayName, {name: <span class="string">'sd'</span>});</span><br></pre></td></tr></table></figure>
<p>这样还有个问题,就是我们每次增加一个事件类型,都需要去修改 <code>EventBusOn</code> 和 <code>EventBusEmit</code> 两个接口,但是他们的修改模式基本是固定的,结合前面的两个技巧,我们也可以优化这个接口。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">enum</span> EventName {</span><br><span class="line"> sayName,</span><br><span class="line"> run,</span><br><span class="line">}</span><br><span class="line"><span class="keyword">interface</span> EventParams {</span><br><span class="line"> [EventName.sayName]: {</span><br><span class="line"> name: <span class="built_in">string</span>;</span><br><span class="line"> };</span><br><span class="line"> [EventName.run]: {</span><br><span class="line"> duration: <span class="built_in">number</span>;</span><br><span class="line"> };</span><br><span class="line">}</span><br><span class="line"><span class="keyword">interface</span> EventBusOn {</span><br><span class="line"> <T <span class="keyword">extends</span> EventName><span class="function">(<span class="params">event: T, cb: (<span class="params">params: EventParams[T]</span>) => <span class="built_in">void</span></span>): <span class="params">void</span></span></span><br><span class="line"><span class="function">}</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="params">interface</span> <span class="params">EventBusEmit</span> {</span></span><br><span class="line"><span class="function"> <<span class="params">T</span> <span class="params">extends</span> <span class="params">EventName</span>>(<span class="params">event: T, params: EventParams[T]</span>): <span class="params">void</span></span></span><br><span class="line"><span class="function">}</span></span><br><span class="line"><span class="function"><span class="params">interface</span> <span class="params">EventBus</span> {</span></span><br><span class="line"><span class="function"> <span class="params">on</span>: <span class="params">EventBusOn</span>;</span></span><br><span class="line"><span class="function"> <span class="params">emit</span>: <span class="params">EventBusEmit</span>;</span></span><br><span class="line"><span class="function">}</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="params">const</span> <span class="params">eventBus</span>: <span class="params">EventBus</span> = <span class="params">new</span> <span class="params">Vue</span><span class="params">()</span>;</span></span><br><span class="line"><span class="function"><span class="params">eventBus</span>.<span class="params">on</span>(<span class="params">EventName.sayName, (<span class="params">{name}</span>) => {</span></span></span><br><span class="line"><span class="function"><span class="params"> <span class="built_in">console</span>.log(<span class="params">name</span>);</span></span></span><br><span class="line"><span class="function"><span class="params">}</span>)</span></span><br><span class="line"><span class="function"><span class="params">eventBus</span>.<span class="params">emit</span>(<span class="params">EventName.sayName, {name: 'name'}</span>)</span></span><br></pre></td></tr></table></figure>
<h3 id="利用-is-帮助类型推断"><a href="#利用-is-帮助类型推断" class="headerlink" title="利用 is 帮助类型推断"></a>利用 is 帮助类型推断</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">interface</span> A {</span><br><span class="line"> <span class="keyword">type</span>: <span class="built_in">string</span>;</span><br><span class="line"> data: {</span><br><span class="line"> name: <span class="built_in">string</span>;</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"><span class="keyword">interface</span> B {</span><br><span class="line"> <span class="keyword">type</span>: <span class="built_in">string</span>;</span><br><span class="line"> data: <span class="built_in">boolean</span>;</span><br><span class="line">}</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isA</span>(<span class="params">params: <span class="built_in">any</span></span>) </span>{</span><br><span class="line"> <span class="keyword">return</span> params.type === <span class="string">'A'</span>;</span><br><span class="line">}</span><br><span class="line"><span class="comment">// 这里能够帮助推断出类型</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isA2</span>(<span class="params">params: <span class="built_in">any</span></span>): <span class="title">params</span> <span class="title">is</span> <span class="title">A</span> </span>{</span><br><span class="line"> <span class="keyword">return</span> params.type === <span class="string">'A'</span>;</span><br><span class="line">}</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">params: A | B</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (isA(params)) {</span><br><span class="line"> params.data</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> ((isA2(params))) {</span><br><span class="line"> params.data</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h3 id="泛型的类型限制"><a href="#泛型的类型限制" class="headerlink" title="泛型的类型限制"></a>泛型的类型限制</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">interface</span> A<T <span class="keyword">extends</span> {length: <span class="built_in">number</span>;}> {</span><br><span class="line"> data:T;</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<p>这里就会限制了类型A的data属性必须是有length属性,且length类型为number</p>
<h3 id="infer-关键字"><a href="#infer-关键字" class="headerlink" title="infer 关键字"></a>infer 关键字</h3><p>ts 官方是有提供相关的几个工具类型,也有用到 infer</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Obtain the parameters of a constructor function type in a tuple</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">type</span> ConstructorParameters<T <span class="keyword">extends</span> <span class="keyword">new</span> (...args: <span class="built_in">any</span>) => <span class="built_in">any</span>> = T <span class="keyword">extends</span> <span class="keyword">new</span> (...args: infer P) => <span class="built_in">any</span> ? P : never;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Obtain the return type of a function type</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">type</span> ReturnType<T <span class="keyword">extends</span> (...args: <span class="built_in">any</span>) => <span class="built_in">any</span>> = T <span class="keyword">extends</span> (...args: <span class="built_in">any</span>) => infer R ? R : <span class="built_in">any</span>;</span><br></pre></td></tr></table></figure>
<p>这里我们可以通过 infer 关键字做类型推断,意思有点想,比方说 ReturnType 中我们如果传入的函数的返回值类型是R,则我们把R返回,这个关键字目前来看使用场景还比较少</p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/sh-article/2019/03/18/google鸡蛋问题/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="$SH">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars1.githubusercontent.com/u/17661313?s=460&v=4">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="SZU_SH">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/sh-article/2019/03/18/google鸡蛋问题/" itemprop="url">google鸡蛋问题</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-18T20:00:11+08:00">
2019-03-18
</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/sh-article/categories/算法/" itemprop="url" rel="index">
<span itemprop="name">算法</span>
</a>
</span>
</span>
<span id="/sh-article/2019/03/18/google鸡蛋问题/" class="leancloud_visitors" data-flag-title="google鸡蛋问题">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数:</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>之前在 leetcode 上看到了一道题 <a href="https://leetcode.com/problems/super-egg-drop/" target="_blank" rel="noopener">Super Egg Drop</a>, 刚好之前看到过一到很类似的题,就是 google 的一道经典的面试题。这里记录一下自己整个的解题思路。</p>
<h3 id="google-原题"><a href="#google-原题" class="headerlink" title="google 原题"></a>google 原题</h3><p>给你两个鸡蛋,它们有可能都在某一层楼往下摔就会摔碎,也可能从一百层楼摔下来没事。有座100层的建筑,要你用这两个鸡蛋通过最少的次数确定哪一层是鸡蛋摔碎的临界点。每次实验即使没摔碎也不会对鸡蛋有损耗。</p>
<h3 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h3><p>这是一道很经典的需要用到动态规划的题目,我们每一次扔鸡蛋的结果都会影响我们后续扔的次数,比方说我们上来就从 90 层扔,如果碎了,我们就得从1楼一层一层往上扔到90层才能试出结果,如果没碎,我们只需要在 90 ~ 100 这 10 层做实验即可。</p>
<p>要用动态规划的来解这道题,我们首先要列出问题中的状态<br>每次我们扔鸡蛋的时候,可能会出现两种状态</p>
<ul>
<li>摔碎,这时下一个鸡蛋就要从最底层一个一个往上试才能试出结果</li>
<li>没碎,则我们需要根据剩余的楼层数来决策出我们下一次丢鸡蛋的楼层数</li>
</ul>
<p>我们假设第一次我们从 x 层楼往下扔,如果鸡蛋没碎,下一次我们往上走 k 层楼再扔,根据我们的假设我们可以绘制出一个这样的决策树。<br><img src="https://user-gold-cdn.xitu.io/2019/2/3/168b26a84805078f?w=465&h=364&f=png&s=26875" alt="01.png"><br>为了让最坏的情况不太坏,我们必须要保证每一次的决策最后所需要的次数都尽可能的相等。也就是<br>1 + k = x。所以每次鸡蛋没碎,我们都要再上一次上升楼层数的基础减少1。</p>
<h4 id="如何确认第一次扔的高度"><a href="#如何确认第一次扔的高度" class="headerlink" title="如何确认第一次扔的高度"></a>如何确认第一次扔的高度</h4><p>我们假设我们每次扔鸡蛋都没有碎,第一次从x层开始扔,我们最后一次就必须在100层楼扔了。可以得到式子 x + x - 1 + x - 2 … + 1 >= 100,根据等差数列求和,我们可以得到 <code>x * (x + 1)/2</code> >= 100,<br>得到 x >= 13.45,因为 x 只能取整数,所以第一次我们从14层楼开始扔,得到最坏情况下,我最多需要扔14次可以确认临界点。</p>
<p>放宽到一般情况,n 层楼 2 个鸡蛋,我们可以得到 x + x - 1 + x - 2 … + 1 >= n<br>最后算出 x >= <img src="https://user-gold-cdn.xitu.io/2019/2/3/168b27b749450dd9?w=111&h=40&f=gif&s=509" alt="02.png"></p>
<h3 id="Super-Egg-Drop"><a href="#Super-Egg-Drop" class="headerlink" title="Super Egg Drop"></a>Super Egg Drop</h3><p><a href="https://leetcode.com/problems/super-egg-drop/" target="_blank" rel="noopener">Super Egg Drop</a> 这道题是 google 这道题的升级版。这里的是给定 K 个鸡蛋,N层楼让你求出最小的次数是多少。</p>
<p>我们还是按照动态规划的思路来列出问题中的状态:</p>
<ul>
<li>K = 0的时候,我们是试不出来的</li>
<li>K = 1时,我们只能从1楼一层一层往上试,次数为楼层高度 n</li>
<li>K = 2时,情况和上面一样</li>
<li>k > 2时,需要我们单独分析了</li>
</ul>
<p>我们设 dp[k][n] 为 k 个鸡蛋,n 层楼时的最优次数。</p>
<ul>
<li>k = 0 , dp[k][n] = 0</li>
<li>k = 1, dp[k][n] = n</li>
<li>k = 2, dp[k][n] = <img src="https://latex.codecogs.com/gif.latex?%5Cfrac%7B-1+%5Csqrt%7B1+8n%7D%7D%7B2%7D" alt="01"></li>
</ul>
<p>当 k > 2时</p>
<p><img src="https://user-gold-cdn.xitu.io/2019/2/3/168b2802b2152e10?w=700&h=334&f=png&s=28538" alt="02"></p>
<p>假设我们还剩 m 个鸡蛋,还需要实验 n 层楼,此时 1 <= n <= h, 假设我们已经知道了 1 ~ n 层最优解,假设这时候第一次丢的高度为 y ,丢的时候会出现两种情况, 然后可以列出动态方程</p>
<h4 id="碎了"><a href="#碎了" class="headerlink" title="碎了"></a>碎了</h4><p>则此时的最优解为 dp(m - 1, y - 1) + 1</p>
<h4 id="没碎"><a href="#没碎" class="headerlink" title="没碎"></a>没碎</h4><p>则此时的最优解为 dp(m, n - y) + 1</p>
<p>由此我们可以得到 dp(m, n) = min(max(dp(m - 1, y - 1), dp(m, n - y)) + 1), 1<=y< n,由此我们可以递推的得到 dp(K,N)</p>
<p><a href="https://github.com/SHISME/LeetCode/blob/master/src/887/index.js" target="_blank" rel="noopener">JS 实现源码</a></p>
<p>这题后面还需要优化,由于复杂度较高,需要一定的基础,暂时没有继续优化下去</p>
<p>推荐一个人的博客,把这题分析的非常透彻,有兴趣的可以看看<br><a href="https://charlesliuyx.github.io/2018/10/11/%E3%80%90%E7%9B%B4%E8%A7%82%E7%AE%97%E6%B3%95%E3%80%91Egg%20Puzzle%20%E9%B8%A1%E8%9B%8B%E9%9A%BE%E9%A2%98/" target="_blank" rel="noopener">博客地址</a></p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/sh-article/2019/03/13/react-native组件开发/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="$SH">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars1.githubusercontent.com/u/17661313?s=460&v=4">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="SZU_SH">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/sh-article/2019/03/13/react-native组件开发/" itemprop="url">react-native拖动组件开发</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-13T00:16:43+08:00">
2019-03-13
</time>