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 包 - 請善待!
麻省理工學院。