当前位置:网站首页>JS multiple judgment writing
JS multiple judgment writing
2022-06-13 02:42:00 【Zixuan Pavilion】
JavaScript A more elegant way of writing complex judgments
Abstract : Writing code is an art .
original text :JavaScript A more elegant way of writing complex judgments
author :Think.
Fundebug Reprint by authorization , The copyright belongs to the original author .
Premise
We write js Code often encounter complex logical judgment , Usually you can use if/else perhaps switch To achieve multiple conditional judgments , But there's a problem , As the complexity of logic increases , In code if/else/switch It will become more and more bloated , More and more can't understand , So how to write judgment logic more elegantly , This article will show you a try .
for instance
Let's start with a piece of code
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The goods are sold out 4 The opening was successful 5 System cancel */
const onButtonClick = (status)=>{
if(status == 1){
sendLog('processing')
jumpTo('IndexPage')
}else if(status == 2){
sendLog('fail')
jumpTo('FailPage')
}else if(status == 3){
sendLog('fail')
jumpTo('FailPage')
}else if(status == 4){
sendLog('success')
jumpTo('SuccessPage')
}else if(status == 5){
sendLog('cancel')
jumpTo('CancelPage')
}else {
sendLog('other')
jumpTo('Index')
}
}
You can see the click logic of this button through the code : Do two things according to different activities , Send log burying point and jump to corresponding page , You can easily put forward the rewriting scheme of this code ,switch appearance :
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The goods are sold out 4 The opening was successful 5 System cancel */
const onButtonClick = (status)=>{
switch (status){
case 1:
sendLog('processing')
jumpTo('IndexPage')
break
case 2:
case 3:
sendLog('fail')
jumpTo('FailPage')
break
case 4:
sendLog('success')
jumpTo('SuccessPage')
break
case 5:
sendLog('cancel')
jumpTo('CancelPage')
break
default:
sendLog('other')
jumpTo('Index')
break
}
}
Um. , It looks better than if/else It's much clearer , Careful students have also found some tips ,case 2 and case 3 When the logic is the same , The execution statement and break, be case 2 Automatic execution of case 3 The logic of .
At this time, some students will say , There's a simpler way of writing :
const actions = {
'1': ['processing','IndexPage'],
'2': ['fail','FailPage'],
'3': ['fail','FailPage'],
'4': ['success','SuccessPage'],
'5': ['cancel','CancelPage'],
'default': ['other','Index'],
}
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The goods are sold out 4 The opening was successful 5 System cancel */
const onButtonClick = (status)=>{
let action = actions[status] || actions['default'],
logName = action[0],
pageName = action[1]
sendLog(logName)
jumpTo(pageName)
}
The code above does look cleaner , The clever thing about this method is : Take the judgment condition as the attribute name of the object , Treat the processing logic as the property value of the object , When the button is clicked , Through the way of object attribute search to make logical judgment , This kind of writing is especially suitable for the case of monistic condition judgment .
Is there any other way of writing ? yes , we have :
const actions = new Map([
[1, ['processing','IndexPage']],
[2, ['fail','FailPage']],
[3, ['fail','FailPage']],
[4, ['success','SuccessPage']],
[5, ['cancel','CancelPage']],
['default', ['other','Index']]
])
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The goods are sold out 4 The opening was successful 5 System cancel */
const onButtonClick = (status)=>{
let action = actions.get(status) || actions.get('default')
sendLog(action[0])
jumpTo(action[1])
}
It uses es6 Inside Map object , Is it better ?Map Objects and Object What's the difference between objects ?
An object usually has its own prototype , So an object always has a ”prototype” key .
The key of an object can only be a string or Symbols, But a Map The bond of can be any value .
You can go through size Property easily gets a Map Number of key value pairs of , The number of key value pairs of an object can only be confirmed manually .
We need to escalate the problem , Previously, when a button was clicked, only judgment was needed status, Now we need to determine the identity of users :
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The opening was successful 4 The goods are sold out 5 There is inventory but not a group * @param {string} identity Identification :guest Objective state master The dominant state */
const onButtonClick = (status,identity)=>{
if(identity == 'guest'){
if(status == 1){
//do sth
}else if(status == 2){
//do sth
}else if(status == 3){
//do sth
}else if(status == 4){
//do sth
}else if(status == 5){
//do sth
}else {
//do sth
}
}else if(identity == 'master') {
if(status == 1){
//do sth
}else if(status == 2){
//do sth
}else if(status == 3){
//do sth
}else if(status == 4){
//do sth
}else if(status == 5){
//do sth
}else {
//do sth
}
}
}
Forgive me for not writing the specific logic in every judgment , Because the code is too long .
Forgive me for using if/else, Because I see a lot of people still using if/else Write this large logical judgment .
From the example above, we can see that , When your logic is upgraded to binary judgment , Your judgment will double , Your code will double , At this time how to write more relaxed ?
const actions = new Map([
['guest_1', ()=>{
/*do sth*/}],
['guest_2', ()=>{
/*do sth*/}],
['guest_3', ()=>{
/*do sth*/}],
['guest_4', ()=>{
/*do sth*/}],
['guest_5', ()=>{
/*do sth*/}],
['master_1', ()=>{
/*do sth*/}],
['master_2', ()=>{
/*do sth*/}],
['master_3', ()=>{
/*do sth*/}],
['master_4', ()=>{
/*do sth*/}],
['master_5', ()=>{
/*do sth*/}],
['default', ()=>{
/*do sth*/}],
])
/**javascript * Button click event * @param {string} identity Identification :guest Objective state master The dominant state * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The opening was successful 4 The goods are sold out 5 There is inventory but not a group */
const onButtonClick = (identity,status)=>{
let action = actions.get(`${
identity}_${
status}`) || actions.get('default')
action.call(this)
}
The core logic of the above code is : Concatenate two conditions into a string , And through the conditional splicing string as a key , With a processing function as a value Map Object to find and execute , This kind of writing is especially useful when judging multiple conditions .
Of course, if the above code is used Object Object to implement is similar :
const actions = {
'guest_1':()=>{
/*do sth*/},
'guest_2':()=>{
/*do sth*/},
//....
}
const onButtonClick = (identity,status)=>{
let action = actions[`${
identity}_${
status}`] || actions['default']
action.call(this)
}
If some students think it's a bit awkward to spell the query criteria into a string , There's another way , Just use Map object , With Object Object as key:
c
onst actions = new Map([
[{
identity:'guest',status:1},()=>{
/*do sth*/}],
[{
identity:'guest',status:2},()=>{
/*do sth*/}],
//...
])
const onButtonClick = (identity,status)=>{
let action = [...actions].filter(([key,value])=>(key.identity == identity && key.status == status))
action.forEach(([key,value])=>value.call(this))
}
Is it a little more advanced ?
It can also be seen here Map And Object The difference between ,Map You can use any type of data as key.
Let's upgrade the difficulty a little bit now , If guest Under the circumstances ,status1-4 The processing logic is the same , The worst case scenario is :
const actions = new Map([
[{
identity:'guest',status:1},()=>{
/* functionA */}],
[{
identity:'guest',status:2},()=>{
/* functionA */}],
[{
identity:'guest',status:3},()=>{
/* functionA */}],
[{
identity:'guest',status:4},()=>{
/* functionA */}],
[{
identity:'guest',status:5},()=>{
/* functionB */}],
//...
])
A good way to write this is to cache the processing logic functions :
const actions = ()=>{
const functionA = ()=>{
/*do sth*/}
const functionB = ()=>{
/*do sth*/}
return new Map([
[{
identity:'guest',status:1},functionA],
[{
identity:'guest',status:2},functionA],
[{
identity:'guest',status:3},functionA],
[{
identity:'guest',status:4},functionA],
[{
identity:'guest',status:5},functionB],
//...
])
}
const onButtonClick = (identity,status)=>{
let action = [...actions()].filter(([key,value])=>(key.identity == identity && key.status == status))
action.forEach(([key,value])=>value.call(this))
}
This is enough for everyday needs , But seriously , It's rewritten up here 4 Time functionA Still a little upset , If the judgment conditions become particularly complicated , such as identity Yes 3 States ,status Yes 10 States , Then you need to define 30 Processing logic , And often many of these logics are the same , This seems to be what I don't want to accept , That can be done in this way :
const actions = ()=>{
const functionA = ()=>{
/*do sth*/}
const functionB = ()=>{
/*do sth*/}
return new Map([
[/^guest_[1-4]$/,functionA],
[/^guest_5$/,functionB],
//...
])
}
const onButtonClick = (identity,status)=>{
let action = [...actions()].filter(([key,value])=>(key.test(`${
identity}_${
status}`)))
action.forEach(([key,value])=>value.call(this))
}
here Map The advantages of , You can use regular types as key 了 , In this way, there is infinite possibility , If demand becomes , Anyone who guest In case of any situation, send a log burial point , Different status The situation also needs a separate logical treatment , Then we can write like this :
const actions = ()=>{
const functionA = ()=>{
/*do sth*/}
const functionB = ()=>{
/*do sth*/}
const functionC = ()=>{
/*send log*/}
return new Map([
[/^guest_[1-4]$/,functionA],
[/^guest_5$/,functionB],
[/^guest_.*$/,functionC],
//...
])
}
const onButtonClick = (identity,status)=>{
let action = [...actions()].filter(([key,value])=>(key.test(`${
identity}_${
status}`)))
action.forEach(([key,value])=>value.call(this))
}
That is to say, using the characteristics of array loop , Logic that meets the regular criteria is executed , Then you can execute both common logic and individual logic , Because of the existence of regularity , You can open your imagination to unlock more ways to play , This article will not go over .
summary
This article has taught you 8 A kind of logical judgment , Include :
if/else
switch
One dollar judgment : Deposit in Object in
One dollar judgment : Deposit in Map in
When making multiple judgments : take condition Concatenate into a string and save it to Object in
When making multiple judgments : take condition Concatenate into a string and save it to Map in
When making multiple judgments : take condition Save as Object Deposit in Map in
When making multiple judgments : take condition Writing is saved to Map in
thus , This article will also come to an end , May you live in the future , It's not just that if/else/switch.
边栏推荐
- [Dest0g3 520迎新赛] 拿到WP还整了很久的Dest0g3_heap
- Microsoft Pinyin opens U / V input mode
- CV 06 demonstrates backgroundworker
- 05 tabBar导航栏功能
- Mean Value Coordinates
- Paper reading - joint beat and downbeat tracking with recurrent neural networks
- OneNote使用指南(一)
- Opencvshare4 and vs2019 configuration
- Fast Color Segementation
- Termux SSH first shell start
猜你喜欢

Paper reading - joint beat and downbeat tracking with recurrent neural networks

01 初识微信小程序

03 认识第一个view组件

Use of OpenCV 12 findcircuits and drawcircuits
![Leetcode 926. Flip string to monotonically increasing [prefix and]](/img/ca/d23c1927bc32393cf023c748e4b449.png)
Leetcode 926. Flip string to monotonically increasing [prefix and]
![[data and Analysis Visualization] D3 introductory tutorial 1-d3 basic knowledge](/img/a8/468a0c4d4a009e155679898fac4b81.jpg)
[data and Analysis Visualization] D3 introductory tutorial 1-d3 basic knowledge

Graph theory, tree based concept

Matlab: find the inner angle of n-sided concave polygon

Detailed explanation of data processing in machine learning (I) -- missing value processing (complete code attached)

Basic principle of bilateral filtering
随机推荐
01 initial knowledge of wechat applet
[data analysis and visualization] key points of data mapping 7- over mapping
[reading papers] dcgan, the combination of generating countermeasure network and deep convolution
03 recognize the first view component
Special topic I of mathematical physics of the sprint strong foundation program
Leetcode 473. 火柴拼正方形 [暴力+剪枝]
重定向设置参数-RedirectAttributes
Delphi implements adding a column of serial number to the CXGRID list
[common tools] pyautogui tutorial
Summary of innovative ideas of transformer model in CV
House raiding
How to learn to understand Matplotlib instead of simple code reuse
Node uses post to request req Pit with empty body
Understand CRF
[data and Analysis Visualization] D3 introductory tutorial 2- building shapes in D3
Detailed explanation of handwritten numeral recognition based on support vector machine (Matlab GUI code, providing handwriting pad)
Opencv 15 face recognition and eye recognition
Graduation project - campus old thing recycling system based on stm32
数字IC设计——FIFO的设计
Huffman tree and its application