Location>code7788 >text

Confusing Code Appreciation #1

Popularity:243 ℃/2024-10-29 09:44:03

Development work encountered a lot of πŸ’© β›° code, this series on everyone to share & spit a little.

Also sharing a professional programming monitor πŸ‘¨πŸ»β€πŸ’»πŸ‘πŸ» πŸ–₯ that I've been using in depth lately!

We'll update the next installment when we've saved enough material, and feel free to contribute and recommend any good material!

1 Random Loneliness

The goal is to combine the target value with a[0,100)The comparison of the random numbers ofFAILED。

Let's take a look at the code implemented now ↓:

function can(compareTo) {
  return ( * 100) > compareTo
    ? 
    : 
}

πŸ’© Question:, is not called, so the judgment execution value is alwaysNaN。

The final effective judgment code is as follows:

function can(compareTo) {
  return NaN > compareTo
    ? 
    : 
}

NaN with other values for the><= The operations are allfalse So the logic here is not as expected.

When you come across this πŸ’©, do you think to fix it or not!

A little addition: this code has been running for years, suggesting that the execution of this error is consistent with the status quo.

2 Timer to execute once

Scenarios using timers are common, such as delaying the execution of logic once:

But would you say it's hard to see a code like the one below?

const timer = setTimeout(() => {
  clearTimeout(timer)
  ('exec once')
}, 1000)

πŸ’© Question.setTimeout, which itself is executed only once, so here's theclearTimeout Extra.

const timer = setInterval(() => {
  clearInterval(timer)
  ('exec interval once')
}, 1000)

πŸ’© Question.setIntervalfor cyclic execution, this scenario of executing once is recommended to use thesetTimeout 。

The code functions fine, but it's harder to look at for those with code cleanliness issues.

A lot of warehouses have this πŸ’© I don't know who took the lead!

3 Non-essential async

Often I see methods that internally are just synchronization logic, but I don't know what the bad habitual addition of theasync

This causes the return to always be aPromise

async function test() {
  return 'hello'
}

Synchronized fetching of values at the time of the call would requireawait and at the same time the method itself needs to be forced to add theasync!

πŸ’© Problem: Easily destroys the structure of the stock code and even affects the execution order.

Here's the difference between synchronous and asynchronous execution results

It's better to have fewer of these pits.

4 Unnecessary judgment

The return value isboolean time, it is usually possible to simplify away the relevant judgments.

Let's look at the bad case:

function case1() {
  if (xx) {
    return true
  }
  return false
}

function case2() {
  return xx ? true : false
}

πŸ’© Problem: The result of the judgment condition execution would have beenboolean, no need to be redundant.

function case() {
  return Judgment Condition
}

I'm sure most students have encountered this kind of redundant judgment, and if it's to round up the amount of code, then I'd suggest writing more comments.

5 Redundant else-ifs

A fetch configuration scenario: values of the same meaning from different configuration objects

function getConfigValue(type, cfg) {
  if (type === 'xxx') {
    return
  }
  else if (type === 'yyy') {
    return
  }
  else if (type === 'zzz') {
    return
  }
  // Dozens of judgments are omitted here。。。
}

πŸ’© Problem: too high a concentration of repeats, a screen full of theseelse-if

Personally, I prefer to make this scenario configurable, easy to expand, do not have to change the code frequently.

const config = {
  xxx: 'id',
  yyy: 'key',
  zzz: 'secret',
}

function getConfigValue(type, cfg) {
  return cfg[config[type]]
}

Guess whoever wrote the first edition probably only wrote a couple ofelse-if And then the people behind the modifications just keepCV, which is what led to the current redundancy.

6 Pseudo-synchronous execution

There's a feature on the page that goes on and off, let's see what's going on πŸ€”.

Look at the code call:

async function mounted() {
  await getProductList()
  await getUserInfo()
  await getUserTags()
  // Other processing code is omitted here
}

mounted()

One might want to start by empirically speculating on the possible reasons why a piece of code functions well and sometimes badly.

Revealed below

const data = {}

async function getProductList() {
  request('productList').then((res) => {
     = res
  })
}

function getUserInfo() {
  return ()
}

async function getUserTags() {
  request('userTags', {
    ids: (item => )
  }).then((res) => {})
}

πŸ’© Problem: Asynchronous methods return inside without waiting for the internal logic to finish executing before they end prematurely

The reason it's good and bad depends on the network, if the interface request is fast you get the dependent data, if it's slow you don't.

The correct way to write this is to wait for all internal asynchronies to finish, or to return the result of their execution, otherwise the default return value is(undefined)

async function rightCode() {
  return request('/api')
}

async function rightCode() {
  await request('/api')
}

This issue has been dealt with several times in one project, and I can't say that it's been done carelessly every time, right?The person who wrote it really just didn't study hard enough!

7 Unintended sequence of implementation

Scenario: there is an interface to return the result of a regular call interface, the return result is null, according to the ok value of the true or false to take a different tout value

const { result, ok } = await fetchData()
const data = result || ok ? obj1 : obj2

If you can't see what the problem is, let's take a look at what the run below shows.

// Expect to return 1
const value1 = 1 || 2 ? 3 : 4

// Returns 3

πŸ’© QUESTION: The reason it's not the same is that theLogical or || Operators have a higher priority thanternary expression

In such cases, it is recommended that students who are unfamiliar with the program be given preference.() Handling of executed code blocks

const data = result || (ok ? obj1 : obj2)

8 v-for unskilled

β‘  Remove the list element

<script setup>
function handleDelete(item) {
  ((item =>  === id), 1)
}
</script>

<template>
  <ul>
    <li v-for="item in list1" :key="" @click="handleDelete(item)">
      {{  }}
    </li>
  </ul>
</template>

β‘‘ Add default key for list rendering

<script setup>
import { onMounted } from 'vue'

onMounted(async () => {
  const data = await getData()
  for (let i = 0; i < ; i++) {
    ({ ...data[i], id: i })
  }
})
</script>

<template>
  <ul>
    <li v-for="item in list2" :key="">
      {{  }}
    </li>
  </ul>
</template>

πŸ’© Question:v-for The traversal array itself provides the subscriptidx。

<template>
  <ul>
    <li v-for="(item, idx) in list2" :key="idx" @click="handleDelete(idx)">
      {{  }}
    </li>
  </ul>
</template>

The functionality is fine, but it's not elegant and the knowledge learning is not there.

9 Redundant and repetitive code

β‘  Repeated string splicing

const baseURL = {
  dev:  + '//' +  'domain1',
  test:  + '//' +  'domain2',
  st:  + '//' +  'domain3',
  prod:  + '//' +  'domain4',
  mock:  + '//' +  'domain5',
}

const host = baseURL[env]

πŸ’© Problem: writing is somewhat redundant, room for simplification

const baseURL = {
  dev: 'domain1',
  test: 'domain2',
  st: 'domain3',
  prod: 'domain4',
  mock: 'domain5',
}

const host = `${}//${baseURL[env]}`

best practice It's still injected through the build tool, which avoids having values from other environments in the code.

const host = `${}//${.VUE_APP_DOMAIN}`

Why pull it out and spit it out, because this kind of code is found in single component repositories, and C-end scenarios when dozens of components are introduced to the page, there is a lot more duplicate code.

β‘‘ CSS Redundant Writing

.box {
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 10px;
  margin-right: 10px;
}

πŸ’© Problem: attributes that can be abbreviated are not abbreviated

.box {
  margin: 10px;
}

testimonialsA shortened version of the commonly used attribute performance shorthand.

10 Hand rubbing getQuery

Let's look at the code for "hand rubbing".

function getQuery() {
  const query = {}
  const href = 
  const searchArray = ('?')[1].split('&')
  (item => {
    const [key, value] = ('=')
    query[key] = value
  })
  return query
}

πŸ’© Problem: only the case with Query is considered, calling it without Query reports an error

('?')[1].split
// Cannot read properties of undefined (reading 'split')

Of course, there are optimizations to be made. location provides a search attribute that can be used directly.

function getQuery() {
  const search = 
  if(!search){
    return {}
  }
  return search
    .slice(1)
    .split('&')
    .reduce((acc, cur) => {
      const [key, value] = ('=')
      acc[key] = value
      return acc
    }, {})
}

built-inURLSearchParams object, you can directly parse theQuery。

function getQuery() {
  const searchParams = new URLSearchParams()
  return (
    ()
  )
}

Compatibility permitting, it is preferred to recommend the use of built-in objects or methods to implement functionality


Eyes get tired easily when you look at the screen for too long? Here's a NB peripheral to share.

Coding "physical plug-ins"

Don't scratch away 🀭, there's content behind πŸ™πŸ»!

Recent in-depth use of a"For Programmers Only" monitor (computer)BenQ RD280U, share a couple of places that I think are great!

/zh-cn/monitor/programming/

IDE Coding Display Optimization

Can you imagine a monitor that actually offers display optimization specifically for the coding IDE!

Touch the logo to toggle dark/bright mode.

Compare the display to other monitors!

Samsung S32A600N BenQ RD280U

It's relatively obvious that the latter is optimized for a better display, while the screen is more resistant to ambient lighting, and the former has a slight whitish reflection when it's too bright indoors.

It's also true that your eyes look more comfortable when you use it πŸ‘πŸ»!

Super Nice Night Mode

It has its own backlight, while the screen brightness and other display effects can be automatically adjusted to adapt to the ambient light intensity!

Turn off all the lights in the room, the effect is as follows

display effect backlight

BenQ RD280UWhen there is no ambient light, the use experience is also very good πŸ‘πŸ», the eyes will not have discomfort, the screen is not white.

Rest Reminder

set up

The monitor comes with a timed break reminder (pop-up window in the lower right corner of the screen),πŸ‘¨πŸ»β€πŸ’» Most of the day-to-day time is spent sitting, with this reminder to drink water & go to the restroom & stand one stop couldn't be better!

It's a lot less work than installing all kinds of reminder software!

Supporting Software Features

The monitor has an accompanying software that has some enhancements in addition to completing the functions of the hardware configuration!

Configuration window desktop partition Auto Tasks & Switching

β‘  Desktop Partition

This is awesome, the Mac system itself is weak in application partitioning and needs software to make up for that.

Drag a window to automatically evoke it at the mouse, select the target partition, and the window will automatically fit.

β‘‘ Automatic Tasks

Different automated task processes can be set up with different modesOne-touch opening of a set series of applications while the screen adjusts to the corresponding preset state。

This function is also very nice, one button switch work/entertainment mode. You don't have to choose to keep the apps you had before shutting down when you turn off your computer.

Let's move on to "Code Tasting."

11 Redundant value-taking judgments

Scenario: deep nesting, value judgment with very long variable names.

function isOk(){
  return (
    testData && 
     && 
     && 
     === 'test' &&
     === 'ok'
  )
}

πŸ’© Problem: Stinky, long judgments that are harder to look at

After using the optional chain

function isOk(){
  return (
    testData?.helloResult?.infoDetail?.type === 'test' &&
    testData?.helloResult?.infoDetail?.status === 'ok'
  )
}

It's important to keep up to date with new grammar.

12 Inexplicable conversions

Look directly at the code

Further processing is done only when a value is judged

const value = await fetchData()

if(value && String(value)){
  // further processing
}

πŸ’© Question: plusString Isn't converting and then judging it just adding insult to injury?

Have any of you in front of the screen encountered πŸ€¦πŸ»β€β™€οΈ

13 For loops everywhere

β‘  Completion of data in case of insufficient quantity

const data = await fetchData()
const count = (, MIN_COUNT)
for (let i = 0; i < count; i++) {
  if(!data[i]){
    data[i] = {
      id: randomId(),
      otherKey: 'default'
    }
  }
}

πŸ’© Problem: Meaningless traversal exists regardless of sufficient number!

const data = await fetchData()
const addedCount = MIN_COUNT - 
for(let i = 0; i < addedCount; i++){
  ({
    id: randomId(),
    otherKey: 'default'
  })
}

Of course it is possible to use the more elegant method to generate a new array to complete the data padding.

const data = await fetchData()
if( < MIN_COUNT){
  const addedData = ({length: MIN_COUNT - }, () => ({
    id: randomId(),
    otherKey: 'default'
  }))
  (...addedData)
}

β‘‘ Filter data according to conditions

const data = await fetchData()
const result = []
for (let i = 0; i < ; i++) {
  if(data[i].value>xx){
    (data[i])
  }
}

πŸ’© Problem: Filtering Scenarios Prioritize Recommended Usesfilter methodologies

const data = await fetchData()
const result = (item => >xx)

β‘’ Add data fields

const data = await fetchData()
for (let i = 0; i < ; i++) {
  data[i].newField = getNewField(data[i])
}

πŸ’© Problem: This scenario suggests the use of themap method, nor does it affect the original array

const data = await fetchData()
const newData = (item => ({
 ...item,
  newField: getNewField(item)
}))

Some people really only know how tofor The basic cycle a carboxylic acid!

ultimate

There are only a handful of people who genuinely enjoy writing code, and there is an overabundance of straw men πŸ€¦πŸ»β€β™€οΈ!