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>) {
@MauricioRobayo
MauricioRobayo / 0-parallel.js
Last active January 31, 2023 16:19
Parallel async await
const p1Promise = p1();
const p2Promise = p2();
const r1 = await a1;
const r2 = await a2;
const Direction = {
Up: 0,
Down: 1,
Left: 2,
Right: 3,
} as const;
type Direction = typeof Direction[keyof typeof Direction];
function run(dir: Direction) {}
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 / optionalChainingOperator.txt
Last active August 15, 2022 19:53
Optional chaining operator
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
@MauricioRobayo
MauricioRobayo / testingAsynchronousCode.js
Last active August 15, 2022 18:26
Testing Asynchronous Code
test('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
test('the fetch fails with an error', async () => {
expect.assertions(1);
try {
await fetchData();
} catch (e) {
@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;
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+(?=%):
Absence of structure is more structured than bad structure.