Skip to content

Instantly share code, notes, and snippets.

View MauricioRobayo's full-sized avatar
🧰
Refactoring

Mauricio Robayo MauricioRobayo

🧰
Refactoring
View GitHub Profile
import { ComponentPropsWithoutRef, ElementType, ReactNode } from "react";
import "./styles.css";
interface Component1Props<T extends ElementType = "div"> {
as?: T;
children: ReactNode;
}
type Props<T extends ElementType> = Component1Props<T> &
Omit<ComponentPropsWithoutRef<T>, keyof Component1Props<T>>;
function Component1<T extends ElementType>({ children, as }: Props<T>) {
It's much easier to recover from no abstraction, than the wrong abstraction.
Abstractions come with a significant cost and a significant risk.
It's better to under-abstract to begin with.
Start with a few abstractions and lots of repetitions. Find repetitive patterns. If the pattern doesn't lead to bugs, don't fix it. It might look ugly but it's not hurting anyone. Try to generalize it and you risk adding bugs in the generalization. It only adds surface area to everyone.
The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded. If the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render:
@MauricioRobayo
MauricioRobayo / promise-type.ts
Created August 3, 2022 03:22
Infer returned type of a promise
type PromiseReturnType<T> = T extends Promise<infer R> ? R : T;
Absence of structure is more structured than bad structure.
@MauricioRobayo
MauricioRobayo / do-loop.js
Created July 17, 2022 15:03
Execute while condition at end of loop
export function isNextMondayHoliday(date: Date): boolean {
const currentDate = new Date(date);
do {
currentDate.setUTCDate(currentDate.getUTCDate() + 1);
} while (currentDate.getUTCDay() !== DayOfWeek.MONDAY);
return isHoliday(currentDate);
}
@MauricioRobayo
MauricioRobayo / derive-it.txt
Last active June 23, 2022 03:55
Don't Sync State. Derive It!
So next time you're maintaining the state of your app and trying to figure out a synchronization bug, think about how you could make it derived on the fly instead.
Lookahead
The syntax is: X(?=Y), it means "look for X, but match only if followed by Y". There may be any pattern instead of X and Y.
For an integer number followed by %, the regexp will be \d+(?=%):
const Direction = {
Up: 0,
Down: 1,
Left: 2,
Right: 3,
} as const;
type Direction = typeof Direction[keyof typeof Direction];
function run(dir: Direction) {}
Use a service layer for your business logic.
In this layer there should not exists any form of 'SQL query', use the data access layer for that.
- Move your code away from the express.js router
- Don't pass the req or res object to the service layer
- Don't return anything related to the HTTP transport layer like a status code or headers from the service layer.