match operator
0.2.1
PHP verfügt über eine Kontrollstruktur namens match, die ab PHP8.0 eingeführt wurde.
Es ist wie eine Vereinfachung der switch
.
Beispiel:
$ 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
Dieses Paket ist ein Versuch, diese Kontrollstruktur so nah wie möglich an eine JS-Funktion zu portieren.
Beispiel:
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
Sie können eine Reihe von Themen verwenden, wenn Sie sie besser lesbar finden.
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
Dies ist mein erstes Typescript-Paket – bitte seien Sie nett!
MIT.