This is a non-exhaustive list of the coding patterns the WorkWave RouteManager's front-end team follows. The patterns are based on years of experience writing, debugging, and refactoring front-end applications with React and TypeScript but evolves constantly. Most of the possible improvements and the code smells are detected during the code reviews and the pair programming sessions.
(please note: I do not work for WorkWave anymore, these patterns will not be updated)
(last update: 2022, March)
Prefer Array.map / Array.filter over Array.reduce
Sometimes, you don't need Array.reduce
and both Array.map
and Array.filter
are more readable.
// ❌ don't
const evenNumbers = [1, 2, 3].reduce<number[]>((acc, item) => {
if(item % 2 === 0) {
acc.push(item)
}
return acc
}, [])
// ✅ do
const evenNumbers = [1, 2, 3].filter(item => item % 2 === 0)
Use Array.some
A lot of times, we forget using Array.some
.
// ❌ don't
const someCustomOff = !!customs.find(mode => mode === 'off')
// ✅ do
const someCustomOff = customs.some(mode => mode === 'off')
Use label and breaks
Controlling nested loops is easier with labels.
// ❌ don't
for(const route of routes) {
for(const order of route.orders) {
for(const pod of order.pods) {
if(pod.id === selectedId) {
foundPod = pod
}
}
if(foundPod) {
break
}
}
if(foundPod) {
break
}
}
// ✅ do
routeLoop: for(const route of routes) {
for(const order of route.orders) {
for(const pod of order.pods) {
if(pod.id === selectedId) {
foundPod = pod
break routeLoop
}
}
}
}
For...of
Classic for
loops allow using continue
and break
, precious to save computations in long loops. for...of
is the most complete for
loop because support Map
, Set
, and Promises
.
// ❌ don't
for(let i = 0; i < array.length; i++) {
const item = array[i]
/* ... rest of the code... */
}
// ✅ do
for(const item of array) {
/* ... rest of the code... */
}
Top comments (0)