var arr =[1,2]functiongenerator(arr){var i =0;return{next(){var done = i > arr.length ?true:false,value = done ?'undefined': arr[i++];return{value : value,done : done}}}}var gen =generator(arr);
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
應用一
n個函數,點一次執行一個
順序執行
用return false來中斷執行
var fn =[functiontest1(){console.log(1);returntrue},functiontest2(){console.log(2);returnfalse},functiontest3(){console.log(3);returntrue}]for(var i of fn){if(!i()){break}}
中間件
node express 洋蔥模型
表單校驗?獲取驗證碼+登錄+請求?獲取token+校驗token+打開頁面?
遞歸 + 函數用next()控制下一次執行
用done控制傳入數組內方法的執行
在每個方法里按具體業務控制next的執行
;(function(functions){function*doFun(arr){for(var i =0; i < arr.length; i++){yield arr[i];}}var iterator =doFun(functions);varinit=()=>{nextDo(iterator.next())}functionnextDo(fn){fn.value(function(){var fn = iterator.next();if(!fn.done){nextDo(fn)}else{return}})}init()})([functiontest1(next){console.log(1);next()},functiontest2(next){console.log(2);next()},functiontest3(next){console.log(3);next()}])
模塊化
// middleware.jsexportconstM=function(functions){function*doFun(arr){for(var i =0; i < arr.length; i++){yield arr[i];}}var iterator =doFun(functions);varinit=()=>{nextDo(iterator.next())}functionnextDo(fn){fn.value(function(){var fn = iterator.next();if(!fn.done){nextDo(fn)}else{return}})}init()}M([functiontest1(next){console.log(1);next()},functiontest2(next){console.log(2);// 偽代碼// if(token){// next()// }next()},functiontest3(next){console.log(3);next()}])
打印日志
TJ co/test/generator
var assert =require('assert');var co =require('..');functionsleep(ms){returnfunction(done){setTimeout(done, ms);}}function*work(){yieldsleep(50);return'yay';}describe('co(*)',function(){describe('with a generator function',function(){it('should wrap with co()',function(){returnco(function*(){var a =yield work;var b =yield work;var c =yield work;assert('yay'== a);assert('yay'== b);assert('yay'== c);var res =yield[work, work, work];assert.deepEqual(['yay','yay','yay'], res);});})it('should catch errors',function(){returnco(function*(){yieldfunction*(){thrownewError('boom');};}).then(function(){thrownewError('wtf')},function(err){assert(err);assert(err.message =='boom');});})})})
LeetCode:二叉樹相關應用 基礎知識 617.歸并兩個二叉樹 題目 Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new …
Tree Shaking
生產環境去除沒有使用到的內容(開發環境沒有刪除,會影響調試)只支持ESM規范(靜態引入,編譯時引入),不支持CJS(動態引入,執行時引入)
// webpa…