模式匹配(patternmatching)是lisp、rust、scala、erlang等语言的常用语法,但是JavaScript一直不支持这个特性,虽然tc39已经有相关提案https://github.com/tc39/proposal-pattern——匹配,但是目前进展缓慢,所以开发了一个babel插件来支持JavaScriptbabel-plugin-proposal-pattern-matching中模式匹配的语法安装使用npm:npminstall--save-devbabel-plugin-proposal-pattern-matchingsetup.babelrc{"plugins":["babel-plugin-proposal-pattern-matching"]}一些演示简单使用importmatchfrom'babel-plugin-proposal-pattern-matching/match'constfib=n=>匹配(n)((v=1)=>1,(v=2)=>1,_=>fib(_-1)+fib(_-2))console.log(fib(10))//->55直接返回一个函数,函数式编程importmatchfrom'babel-plugin-proposal-pattern-matching/match'constfib=fnmatch((v=1)=>1,(v=2)=>1,_=>fib(_-1)+fib(_-2))console.log(fib(10))//->55constarr=[1,2,3]console.log(arr.map(fnmatch((v=1)=>'一',(v=2)=>'二',(v=3)=>'三')))//->['one','two','three']数据类型判断import{match,T}来自'babel-plugin-proposal-pattern-matching/match'constgetType=item=>match(item)((v=T.number)=>'number',(v=T.string)=>'string',(v=T.nullish)=>'nullish',_=>`${_}undefinedtype`)console.log(getType('a'))//->stringconsole.log(getType(1))//->numberconsole.log(getType(undefined))//->nullishconsole.log(getType(null))//->nullish实例判别import{match,instanceOf}from'babel-plugin-proposal-pattern-matching/match'constgetType=val=>match(val)((v=instanceOf(RegExp))=>'RegExp',(v=instanceOf(Array))=>'Array',(v=instanceOf(Object))=>'Object',)console.log(getType(/111/))//->RegExpconsole.log(getType([1,2,3]))//->Arrayconsole.log(getType({a:1}))//->对象解析,这里支持无限嵌套import{match}from'babel-plugin-proposal-pattern-matching/match'constsum=x=>match(x)(([x,...xs])=>x+sum(xs),([])=>0)console.log(sum([1,2,3]))//->6for(leti=1;i<=15;i++){console.log(match({a:i%3,b:i%5})(({a=0,b=0})=>'FizzBu??zz',({a=0,b})=>'嘶嘶声',({a,b=0})=>'嗡嗡声',_=>i))}//->//1//2//Fizz//4//Buzz//Fizz//7//8//Fizz//Buzz//11//Fizz//13//14//FizzBu??zz非运算导入{match,not,or,T}来自'babel-plugin-proposal-pattern-matching/match'consttoNumber=n=>match(n)((v=not(T.boolean))=>v,(v=true)=>1,(v=false)=>0)console.log([true,false,0,1,2,3].map(toNumber))//->[1,0,0,1,2,3]或运算导入{match,or}from'babel-plugin-proposal-pattern-matching/match'constfib=n=>match(n)((v=or(1,2))=>1,_=>fib(_-1)+fib(_-2))console.log(fib(10))//->55与运算import{match,and,not}from'babel-plugin-proposal-pattern-matching/match'constfib=n=>match(n)((_=and(not(1),not(2)))=>fib(_-1)+fib(_-2),_=>1)console.log(fib(10))//->55
