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…