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 パッケージです - 親切にしてください。
マサチューセッツ工科大学。