9999 return result . concat ( left , right )
100100 }
101101 }
102+
103+ /**
104+ * A
105+ * B C
106+ * D E F G
107+ */
108+ let tree = {
109+ 'A' : [ 'B' , 'C' ] ,
110+ 'B' : [ 'D' , 'E' ] ,
111+ 'C' : [ 'F' , 'G' ]
112+ }
113+ // 深度优先搜索
114+ function dfs ( tree , node , list = [ ] ) {
115+ list . push ( node )
116+ let child = tree [ node ]
117+ child && child . forEach ( e => dfs ( tree , e , list ) )
118+ return list
119+ }
120+ // console.log(dfs(tree, 'A'));
121+
122+ // 广度优先搜索
123+ function bfs ( tree , node , list = [ ] ) {
124+ let stack = [ node ]
125+ while ( stack . length ) {
126+ let child = stack . shift ( )
127+ list . push ( child )
128+ tree [ child ] && stack . push ( ...tree [ child ] )
129+ }
130+ return list
131+ }
132+ // console.log(bfs(tree, 'A'));
102133
103- console . log ( 'start: ' , arr ) ;
104- console . log ( 'end: ' , insertSort ( arr ) ) ;
105-
134+ // 节流
135+ // 如果一个函数持续地触发,那么在固定的事件执行一次
136+ function throttle ( fn , ms = 1000 ) {
137+ let cd = true
138+ return function ( ) {
139+ if ( ! cd ) return
140+ cd = false
141+ setTimeout ( _ => {
142+ fn . apply ( this , arguments )
143+ cd = true
144+ } , ms )
145+ }
146+ }
147+ // 防抖
148+ // 如果一个函数持续地触发,那么只在它结束后过一段时间只执行一次
149+ function debounce ( fn , ms = 1000 ) {
150+ let timer = null
151+ return function ( ) {
152+ clearTimeout ( timer )
153+ timer = setTimeout ( _ => {
154+ fn . apply ( this , arguments )
155+ } , ms )
156+ }
157+ }
158+ function sayHi ( name ) {
159+ console . log ( name ) ;
160+ }
161+ let fn = debounce ( sayHi )
162+ window . onmousemove = function ( ) {
163+ fn ( 'debounce: hans' )
164+ }
165+ let fn2 = throttle ( sayHi )
166+ setInterval ( _ => {
167+ fn2 ( 'throttle: hans' )
168+ } , 10 )
106169</ script >
107170</ html>
0 commit comments