Skip to content

Instantly share code, notes, and snippets.

@t3dotgg
t3dotgg / try-catch.ts
Last active April 26, 2025 18:55
Theo's preferred way of handling try/catch in TypeScript
// Types for the result object with discriminated union
type Success<T> = {
data: T;
error: null;
};
type Failure<E> = {
data: null;
error: E;
};
@mberneti
mberneti / retryDynamicImport.ts
Last active March 16, 2025 07:13
This utility function retryDynamicImport enhances React’s lazy loading mechanism by adding retry logic with a versioned query parameter. It retries importing a component multiple times in case of failure, which can be useful for bypassing browser cache or dealing with intermittent network issues. It can be used as a drop-in replacement for React…
// Usage:
// Replace React.lazy(() => import('x'));
// with retryDynamicImport(() => import('x'));
import { ComponentType, lazy } from 'react';
const MAX_RETRY_COUNT = 15;
const RETRY_DELAY_MS = 500;
// Regex to extract the module URL from the import statement
@luismramirezr
luismramirezr / node-js-multi-threading.md
Created May 19, 2023 19:40
Concurrency, Parallelism, and Multi-threading in Node.js

Concurrency, Parallelism, and Multi-threading in Node.js

In the world of computing, the terms "concurrency" and "parallelism" are often used interchangeably, but they represent distinct concepts with significant implications for optimizing performance and efficiency. To understand better how Node.js, with its single-threaded event loop, works with concurrency and parallelism, let's first explore the fundamental differences between concurrency and parallelism and then dive into the event loop in Node.js, its role in implementing concurrency and parallelism, and how it differs from traditional multithreading approaches.

Concurrency: "Simultaneous" Execution

Concurrency refers to the ability of a computer system to execute multiple tasks concurrently. It involves breaking down a complex problem into smaller, independent tasks that can be executed in overlapping time intervals. While the tasks may appear to be executing simultaneously, they are actually taking turns running on a single processor or core. Co

@mahdikhashan
mahdikhashan / DateTimeFormatMock.js
Created March 28, 2023 12:15
Vitest Mock Timezone
it("should get the client timezone as a string", () => {
const DateTimeFormat = Intl.DateTimeFormat;
vi.spyOn(global.Intl, "DateTimeFormat").mockImplementation(
(locale, options) =>
new DateTimeFormat(locale, { ...options, timeZone: "Asia/Tehran" })
);
const date: MyDate = new MyDate("2023-03-28T11:06:48+00:00");
expect(date.getClientTZ()).toEqual("Asia/Tehran");
@myesn
myesn / logto-auth.guard.ts
Created October 20, 2022 08:52
NestJS Logto Auth Guard
import {
Injectable,
CanActivate,
ExecutionContext,
HttpStatus,
BadRequestException,
UnauthorizedException,
} from '@nestjs/common';
import { Request } from 'express';
import { ConfigService } from '@nestjs/config';
@getify
getify / 1-CalendarItem.js
Last active March 21, 2024 09:11
an illustration (non-trivial example) of many newer JS class features
// abstract class, not intended to be instantiated directly
class CalendarItem {
static #UNSET = Symbol("unset")
static #isUnset(v) {
return v === this.#UNSET;
}
static {
for (let [idx,msg] of [
"ID is already set.",
"ID is unset.",
@getify
getify / 1.md
Last active March 2, 2023 21:24
In defense of using blocks to create localized scope for variables... (part 1 of 2)
@etherx-dev
etherx-dev / requires python binanace api
Last active January 26, 2025 23:49
Crypto Currency address Regular Expressions - extracted from the binance api on 31/03/2022
from binance.client import Client
from binance.exceptions import BinanceAPIException, BinanceRequestException
#incomplete but i just need a useful regex
client = Client("apikey", "secret")
coininfo = client.get_all_coins_info()
for coin in coininfo:
for network in (coin['networkList']):
print(coin['name'],network['addressRegex'])
@kjmph
kjmph / A_UUID_v7_for_Postgres.sql
Last active April 23, 2025 13:45
Postgres PL/pgSQL function for UUID v7 and a bonus custom UUID v8 to support microsecond precision as well. Read more here: https://datatracker.ietf.org/doc/rfc9562/
-- Based off IETF draft, https://datatracker.ietf.org/doc/draft-peabody-dispatch-new-uuid-format/
create or replace function uuid_generate_v7()
returns uuid
as $$
begin
-- use random v4 uuid as starting point (which has the same variant we need)
-- then overlay timestamp
-- then set version 7 by flipping the 2 and 1 bit in the version 4 string
return encode(
@kpirliyev
kpirliyev / postgresql_13_replication.md
Last active March 10, 2025 12:58
PostgreSQL 13 Master-Slave Streaming Replication

PostgreSQL 13 Master-Standby Streaming Replication

PostgreSQL has various types of replication available and it could be a little bit confusing to figure out what has to be done to just configure a simple master-standby replicated database setup. Digging my way through documentation I decided to write my own little guide on how to setup simple replication in PostgreSQL 13.

How it works

Streaming replication works by streaming the contents of WAL (Write-Ahead Logging) file from one server to another. Each transaction is first written into the WAL file, so essentially every change on the primary server will be replicated on the standby server. Standby server could be used for read-only operations, but can't be written to. Ofcourse, transferring data over the network takes time and there is a small lag before data written to one server becomes available on the other. To guarrantee data consistency on both servers at the time of read operation we can enable synchronous replication mode. This way, datab