match operator
0.2.1
PHP memiliki struktur kontrol bernama match, yang telah diperkenalkan pada PHP8.0.
Ini seperti penyederhanaan struktur kendali switch
.
Contoh:
$ 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
Paket ini merupakan upaya untuk mem-porting struktur kontrol tersebut ke fungsi JS, dengan cara yang paling mendekati.
Contoh:
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
Anda dapat menggunakan berbagai subjek jika Anda merasa lebih mudah dibaca.
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
Ini adalah paket TypeScript pertama saya - mohon berbaik hati!
MIT.