Hello, dear friends, hello, everyone
I don’t know if you’ve ever had a kid in your group write code that’s not standard, that’s not the best way to write it, and there’s a lot of really bad ways to write it. Share this article with them
Today we are going to illustrate how code in a scenario can be readable and maintainable.
log
I think you are certainly familiar with printing logs. But do you write the best log output ever?
For example:
I have three cats
const cat1 = { name: 'Pretty girl'.age: 2.color: 'orange' };
const cat2 = { name: 'Big black egg'.age: 2.color: 'black' };
const cat3 = { name: 'Little tiger'.age: 2.color: 'orange' };
Copy the code
What if I want to see information about the three cats?
/ / 'Bad Code
'
// Is that so?
console.log(cat1);
console.log(cat2);
console.log(cat3);
// Is it true?
console.log(cat1, cat2,cat3);
Copy the code
So let’s look at the output.
The output doesn’t make the variables very intuitive, and if we see this information on the console, we’re probably confused.
So what’s the right way to write it?
/ / 'Good Code
'
console.log('%c My Cats ----->'.'color: orange; font-weight: bold; ')
console.log({ cat1, cat2, cat3 });
Copy the code
Let’s take a look at this simple change, which seems to just put them inside an object, but the most intuitive benefit is that we now have a mapping between content and variables.
If we want to print an array object, the other option is also very good.
That’s the table, so it’s very clear what the data is.
console.table([cat1, cat2, cat3]);
Copy the code
cycle
For example:
const catsWeight = [3000.4900.5200];
Copy the code
My three cats weigh 3000g, 4900g and 5200g respectively. What I want to do is calculate the total weight of the three cats, and the ones that are too fat, over 4500g, and how much weight they would all weigh if they lost half of their weight.
'Bad Loop Code
'
const totalWeight = 0;
const overWeightCats = [];
const reduceHalf = [];
for (i = 0; i < catsWeight.length; i++) {
totalWeight += catsWeight[i];
if (catsWeight[i] > 4500) {
overWeightCats.push(catsWeight[i])
}
reduceHalf.push(catsWeight[i] / 2);
}
Copy the code
'Good Loop Code
'
// Reduce
const totalWeight = catsWeight.reduce((acc, cur) = > acc + cur)
// Map
const reduceHalf = catsWeight.map(c= > c / 2)
// Filter
const overWeightCats = catsWeight.filter(c= > c > 4500);
Copy the code
Or if I want to know if there’s a cat over 5,000 grams, I just want to know if there’s a cat over 5,000 grams, and I don’t care which one it is.
const hasCatWeightOver5000 = catsWeight.some(c= > c > 5000);
Copy the code
For example, I don’t know if my cats are eating well or weighing more than 3,000 grams.
const allCatsOver3000 = catsWeight.every(c= > c > 3000);
Copy the code
Therefore, when we encounter the problem of circulation, we should not go all around the world with one For. It does work, though.
And again, I personally like pure functions, and functions of one function. Such functions are more coherent and readable.
Object property reading
For example:
I have a cat. Its name is Big Black!
const cat = {
name: 'big black'.legs: 4.type: 'Chinese Garden Cat'.age: 2.color: 'black'
}
Copy the code
I want to print information about this cat
/ / 'Bad Code
'
function logInfo(cat) {
return 'My cat's name is${cat.name}, it has${cat.legs}A leg, it's this year${cat.age}It's old. It's a${cat.color}The color of the${cat.type}`;
}
Copy the code
/ / 'Good Code
'
function logInfo({ name, legs, type, age, color }) {
return 'My cat's name is${name}, it has${legs}A leg, it's this year${age}It's old. It's a${color}The color of the${type}`;
}
// OR
function logInfo(cat) {
const { name, legs, type, age, color } = cat;
return 'My cat's name is${name}, it has${legs}A leg, it's this year${age}It's old. It's a${color}The color of the${type}`;
}
Copy the code
${} ${}
const { name, legs, type, age, color } = cat;
const catInfo = 'My cat's name is.'+name+'It's this year'+age+'years old! '
Copy the code
This should also be common in our everyday code.
So it’s time to write it differently
New properties and object copy
For example:
I have a cat. Her name is beautiful girl!
const cat = {
name: 'Pretty girl'.legs: 4.type: 'Chinese Garden Cat'.age: 2.color: 'orange'
}
Copy the code
If I want to get a new object that also contains all the information about the cat.
The previous approach was:
const newCat = Object.assign({}, cat);
Copy the code
Before, we really didn’t have a better way to write it. But now we have ~
constnewCat = {... cat};Copy the code
If I want to add a gender to my cat!
The previous approach was:
cat = Object.assign(cat, { genda: 'male' });
// OR
cat.genda = 'male';
Copy the code
Now we can do this
cat = {... cat,genda: 'male' };
Copy the code
Reading of array values
For example:
I have three cats
const cats = ['big black'.'Pretty girl'.'Little tiger'];
Copy the code
I wonder who the first one and the second one are.
/ / 'Bad Code
'
const first = cats[0];
const second = cats[1];
Copy the code
The following is recommended
/ / 'Good Code
'
const [first, second, ...rest] = cats;
Copy the code
Suppose one day I have two cats
/ / 'Bad Code
'
cats.push('newCat1');
cats.push('newCat2');
Copy the code
The following is recommended
/ / 'Good Code
'
cats = [...cats, 'newCat1'.'newCat2'];
Copy the code
Promise
For example:
I have three cats and hand out dried fish every day. But desiccating fish is an asynchronous job.
const distribute = (name) = > Promise.resolve(`${name}Got the fish! `);
const start = (a)= > Promise.resolve('开始');
Copy the code
/ / 'Bad Code
'
start()
.then((a)= > {
return distribute('big black');
})
.then((a)= > {
return distribute('Pretty girl');
})
.then((a)= > {
return distribute('Little tiger');
})
.then((a)= > {
console.log('Everybody got the dried fish.');
})
Copy the code
/ / 'Good Code
'
Promise.all([
distribute('big black'),
distribute('Pretty girl'),
distribute('Little tiger')
])
.then((a)= > {
console.log('Everybody got the dried fish.');
})
// OR
const first = await distribute('big black');
const second = await distribute('Pretty girl');
const third = await distribute('Little tiger');
Copy the code
If the else and return
First of all, I personally don’t like else very much, and I almost never have else in my code, unless I have to. When used properly, returns greatly increase the readability of your code.
For example:
I have three cute kittens. They all like to get into boxes.
Now the box is on the floor, I want to know if there is a cat in it, if there is no cat, tell me there is no cat, if there is one, tell me who it is, two also tell me who it is, three need not tell me.
/ / 'Bad Code
'
const box = ['big black'.'Pretty girl'.'Little tiger'];
function check(box) {
if(box.length===0) {
console.log('No cat');
} else if(box.length < 3) {
box.forEach(cat= > console.log(cat));
} else{}}Copy the code
/ / 'Good Code
'
const box = ['big black'.'Pretty girl'.'Little tiger'];
function check(box) {
const len = box.length;
if(len === 3) return;
if(len === 0) {
console.log('No cat');
return;
}
box.forEach(cat= > console.log(cat));
}
Copy the code
Well, that’s all for this time
Code specification and writing is a more detailed thing, we need to pay attention to the daily code, think about this place is not a better way to write.
Mien has 5 years of front-end development experience and is currently with Schlumberger.
Scope: Angular, Vue, React, applet, electron, nodeJS, and a bunch of other messy technologies
Welcome to leave your questions and corrections.
I’m Mien and I’ll see you next time.