match operator
0.2.1
PHP有一个名为match的控制结构,从PHP8.0开始引入。
这就像switch
控制结构的简化。
例子:
$ food = ' strawberry ' ;
$ description = match ( $ food ) {
' apple ' => ' This food is an apple ' ,
' strawberry ' , ' raspberry ' => ' This food is a red fruit ' ,
}; // This food is a red fruit
$ food = ' unknown ' ;
$ description = match ( $ food ) {
' apple ' => ' This food is an apple ' ,
' strawberry ' , ' raspberry ' => ' This food is a red fruit ' ,
}; // UnhandledMatchError
$ food = ' unknown ' ;
$ description = match ( $ food ) {
' apple ' => ' This food is an apple ' ,
' strawberry ' , ' raspberry ' => ' This food is a red fruit ' ,
default => ' This food is unknown ' ,
}; // This food is unknown
这个包试图将该控制结构移植到 JS 函数,这是最接近的可能方式。
例子:
import match from 'match-operator'
const food = 'strawberry'
const description = match ( food , [
[ 'apple' , 'This food is an apple' ] ,
[ 'strawberry' , 'raspberry' , 'This food is a red fruit' ] ,
] ) // This food is a red fruit
const food = 'unknown'
const description = match ( food , [
[ 'apple' , 'This food is an apple' ] ,
[ 'strawberry' , 'raspberry' , 'This food is a red fruit' ] ,
] ) // UnhandledMatchError
const food = 'unknown'
const description = match ( food , [
[ 'apple' , 'This food is an apple' ] ,
[ 'strawberry' , 'raspberry' , 'This food is a red fruit' ] ,
[ match . default , 'This food is unknown' ]
] ) // This food is unknown
如果您发现一系列主题更具可读性,则可以使用它。
const description = match ( food , [
[ [ 'strawberry' , 'raspberry' ] , 'This food is a red fruit' ] ,
] )
npm install match-operator --save # If you're using NPM
yarn add match-operator # If you're using Yarn
npm run test # If you're using NPM
yarn test # If you're using Yarn
这是我的第一个 Typescript 包 - 请善待!
麻省理工学院。