In the development process, it is often difficult to read the code because of too much if else. Today, let's solve this problem together to make the code more beautiful, easier to maintain, and more enjoyable for the receiver
A function returns the color according to the type of fruit passed in. The code is as follows:
Write a way
function test(fruit) { if (fruit == 'apple' || fruit == 'strawberry') { console.log('red'); } }
Writing two
function test(fruit) { // Put the same kind into an array const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) { console.log('red'); } }
Multi condition processing in filtering
- Throw out unqualified resources earlier
- Compound specific conditions in final processing
function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // Throw out in advance unqualified if (!fruit) throw new Error('No fruit!'); if (!redFruits.includes(fruit)) return; console.log('red'); // Compound condition to last if (quantity > 10) { console.log('big quantity'); } }
Handle the case that the incoming parameter is an object
- Use deconstruction assignment to solve
Code before optimization
function test(fruit) { if (fruit && fruit.name) { console.log (fruit.name); } else { console.log('unknown'); } } test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple
Optimized code
function test({name} = {}) { console.log (name || 'unknown'); } test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple
Replace switch with map
Pre optimization code
function test(color) { switch (color) { case 'red': return ['apple', 'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; } } test(null); // [] test('yellow'); // ['banana', 'pineapple']
Optimized code
const fruitColor = { red: ['apple', 'strawberry'], yellow: ['banana', 'pineapple'], purple: ['grape', 'plum'] }; function test(color) { return fruitColor[color] || []; }
Code in map mode
const fruitColor = new Map() .set('red', ['apple', 'strawberry']) .set('yellow', ['banana', 'pineapple']) .set('purple', ['grape', 'plum']); function test(color) { return fruitColor.get(color) || []; }
Optimize the project code with the above content
Example: dealing with front-end role management
-
Encapsulate role dictionary and add tool class (in util.js)
// role const roles = { CUSTOMER: { value: 'CUSTOMER', idValue: 'uid', url: '/pages/home/index' }, OIL_ATTENDANT: { value: 'OIL_ATTENDANT', idValue: 'ouid', url: '/pages/oiler/index' } } // Get roles according to key const getRoleByKey = (role) => { return roles[role] || "" } // Get role home page const getRoleUrl = (role) => { return roles[role].url || '' } // Get current user role const checkRoleByIdValue = () => { const app = getApp(); const obj = { uid: 'CUSTOMER', ouid: 'OIL_ATTENDANT' } let currentRole Object.keys(obj).forEach(k => { if (app.globalData[k]) { currentRole = obj[k] } }) return currentRole } // Role id value const roleIdIs = (role) => { return roles[role].idValue }
-
Introducing util method into the page
import { getRoleByKey, getRoleUrl, checkRoleByIdValue } from '../../utils/utils.js' // No longer use if else to judge roles, store data according to the key of different roles, use tool class directly, and do it in one line of code saveGlobalAndStorageSync(`${currentRole.idValue}`,data.userInfo) const roleUrl = getRoleUrl(checkRoleByIdValue())