Javascript's tips for if...else/find/deconstruction/operator optimization

1. Reduce if...else noodle code

const getPrice = (name) => {
    
    
	if (name === 'hamburger') {
    
    
		return 20
	} else if (name === 'French fries') {
    
    
		return 15
	} else if (name === 'ice cream') {
    
    
		return 5
	}
}
console.log(getPrice('hamburger')) // 20

optimization:

const foodMap = {
    
    
	'hamburger' : 20,
	'French fries' : 15,
	'ice cream' : 5,
	'Coffee' : 12
}
const getPrice = (name) => {
    
    
	return foodMap[name]
}
console.log(getPrice('hamburger')) // 20

2. Pipeline operations replace redundant loops

const foods = [{
    
    
	name: 'hamburger',
	group: 1
}, {
    
    
	name: 'French fries',
	group: 1
}, {
    
    
	name: 'Coffee',
	group: 2
}, {
    
    
	name: 'ice cream',
	group: 1
}]

Find the food that belongs to package 1, first filter the array and then reorganize

const names = foods
	.filter( i => i.group === 1 )
	.map( i => i.name )
console.log(names) // ['hamburger', 'French fries', 'ice cream']

3. Find replaces redundant loops

Find specific food according to the attribute value in the food object array

const hamburger = foods
	.find( i => i.name === 'hamburger' && i.group === 1)
console.log(hamburger) // {name: 'hamburger', group: 1}

4. includes replaces redundant loops

A bowl of "Kang Fu Laotan Sauerkraut Beef Noodles" consists of "sauerkraut", "noodles", "beef cubes", "cigarette butts" and "foot skin", then we want to use a function to verify whether there is foot skin in this noodle

const sauerkrautBeefNoodles = ['a' , 'b' , 'c' , 'd']
const hasD = sauerkrautBeefNoodles.includes('d')
console.log(hasD) // true

5. result return value

const getUrl = (content, prefix, suffix) => {
    
    
	let result = content
	if (prefix) {
    
    
		result = `${
      
      prefix}${
      
      result}`
	}
	if (suffix) {
    
    
		result = `${
      
      result}${
      
      suffix}`
	}
	return result
}
console.log(getUrl('www.apifox', 'https://', '.cn')) // https://www.apifox.cn

6. Return early

const activeParentKeys = (selectKeys) => {
    
    
	if (!selectKeys) return []
	if (selectKeys !== 'key1') {
    
    
		return getParentKeys(selectKeys)
	}
	return []
}

7. Keep the object intact

Destructuring the complete object

const getDocDetail = (data) => {
    
    
	const {
    
    icon, content}
	console.log(icon)
	console.log(content)
}
getDocDetail(data)

8. Use operators skillfully

let activeKey = selectedKey || ''

Guess you like

Origin blog.csdn.net/qiaoqiaohong/article/details/124630684