Skip to content

Instantly share code, notes, and snippets.

View AspireOne's full-sized avatar

Matěj Pešl AspireOne

View GitHub Profile
@AspireOne
AspireOne / use-optimistic-update.ts
Last active January 6, 2025 22:42
A Custom hook for automatic, type-safe react-query optimistic updates with proper rollback. Use together with openapi-typescript + openapi-react-query.
import { type paths } from "@/types/api-types";
import { queryClient } from "@/api/api";
import { toast } from "sonner";
type OperationState<TData> = {
previousData: TData;
timestamp: number;
};
// Constants for stack management
@AspireOne
AspireOne / oneline-stats.ps1
Last active January 6, 2025 17:14
One-liners for checking text statistics inside of files
# All command are inside a /src directory and excluding node_modules and files starting with a dot.
# Get amount of characters
(Get-ChildItem -Path ./src -Recurse -File | Where-Object { $_.FullName -notmatch '\\node_modules\\' -and $_.Name -notmatch '^\.' -and $_.Directory.Name -notmatch '^\.' } | ForEach-Object { (Get-Content $_.FullName -Raw).Length } | Measure-Object -Sum).Sum
# Get amount of OpenAI tokens (based on 1 token ≈ 4.325 characters, which I confirmed to be roughly accurate)
[math]::Round(((Get-ChildItem -Path ./src -Recurse -File | Where-Object { $_.FullName -notmatch '\\node_modules\\' -and $_.Name -notmatch '^\.' -and $_.Directory.Name -notmatch '^\.' } | ForEach-Object { (Get-Content $_.FullName -Raw).Length } | Measure-Object -Sum).Sum * 0.23129), 0)
# Ge amount of lines
(Get-ChildItem -Path ./src -Recurse -File | Where-Object { $_.FullName -notmatch '\\node_modules\\' -and $_.Name -notmatch '^\.' -and $_.Directory.Name -notmatch '^\.' } | ForEach-Object { (Get-Content $_.FullName | Where
@AspireOne
AspireOne / Athrottle.service.ts
Created October 28, 2024 15:02
NestJS Request Throttling
import { Injectable, OnModuleInit, Optional, Logger } from "@nestjs/common";
import { ThrottleMetrics } from "./throttle.metrics";
import {
ThrottleConfig,
ThrottleRecord,
ThrottleCheckResult,
ThrottleRule,
} from "./throttle.types";
import { ThrottleException } from "./throttle.exception";
@AspireOne
AspireOne / events.ts
Created October 1, 2024 21:03
Typed events in typescript
type EventMap = {
loadMore: { lastMessage: sting };
};
class TypedEventTarget<T extends Record<string, any>> {
private listeners: Partial<{ [K in keyof T]: ((event: T[K]) => void)[] }> = {};
addEventListener<K extends keyof T>(type: K, listener: (event: T[K]) => void) {
if (!this.listeners[type]) {
this.listeners[type] = [];
@AspireOne
AspireOne / CompatDateTimePicker.tsx
Last active September 28, 2024 19:48
React Native DateTimePicker that is compatible with both iOS and android. The iOS version has an additional Modal wrapper around the DateTimePicker itself.
import * as React from "react";
import { Platform } from "react-native";
import DateTimePicker, {
AndroidNativeProps,
type IOSNativeProps,
} from "@react-native-community/datetimepicker";
import { DateTimePickerModal } from "@/components/DateTimePickerModal";
type CustomProps = {
iosModalLabel: React.ReactNode;
@AspireOne
AspireOne / utils.ts
Created September 25, 2024 22:09
a Zod utility function to make specific fields inside an existing schema nullable. Just provide a (typesage) array of fields to make nullable.
import { z } from "zod";
type NullableKeys<T, K extends keyof T> = Omit<T, K> & { [P in K]: T[P] | null };
export function makeFieldsNullable<T extends z.ZodTypeAny, K extends keyof z.infer<T>>(
schema: T,
keys: K[],
): z.ZodType<NullableKeys<z.infer<T>, K>> {
return schema.transform((data) => {
const result = { ...data };
@AspireOne
AspireOne / extract-dependencies.ts
Last active September 1, 2024 18:13
Generate a comprehensive summary of packages used in your project, along wth links to them, their licenses (fetched from a public database), and warnings for non-permissive licences. Supports caching. You can use this in your pre-commit hook.
import * as fs from "fs/promises";
import * as path from "path";
import fetch from "node-fetch";
import PQueue from "p-queue";
interface PackageJson {
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
}
@AspireOne
AspireOne / create-typed-api-mutation.ts
Last active August 1, 2024 13:57
Typesafe react-query wrapper for openapi-fetch
import type {
FetchError,
ResponseType,
MutationVariablesType,
PathsWithDefinedMethods,
} from "@/types/api-mutators";
import { client } from "@/api/common";
import { createApiMutation } from "@/helpers/create-api-mutation.helper";
// NOTE: WILL NOT WORK WITH "PATH" arguments (if the target API endpoint is e.g. "/user/:id").
@AspireOne
AspireOne / get-structure.py
Created March 31, 2024 14:37
A Python script that gets the folder/file structure of a given web project. Common folders (node_modules, .git) are ignored.
import os
def list_files(startpath, output_file, list_files=True):
ignored_directories = {"node_modules", "out", "ios", "public", "locales", "uploads", "volumes", "prisma", ".husky", ".turbo", "android", ".next", ".github", ".git", ".idea", ".vscode", ".vscode-counter"}
with open(output_file, 'w') as f_out:
for root, dirs, files in os.walk(startpath, topdown=True):
# Update dirs in-place to skip ignored directories
dirs[:] = [d for d in dirs if all(not root.replace(startpath, "").startswith(ignored) and d != ignored for ignored in ignored_directories)]
# Skip files at the root directory
@AspireOne
AspireOne / CzechMonths.cs
Last active November 14, 2020 15:15
This method will return a correctly inclined czech month based on the passed month number and case (C# 8 and C#9 ver.)
static readonly string[] DeclensedCzechMonthNamesBase = { "ledn", "únor", "březn", "dubn", "květn", "červn", "červenc",
"srpn", "září", "říjn", "listopad", "prosinc"};
static readonly string[] FullCzechMonthNames = { "leden", "únor", "březen", "duben", "květen", "červen", "červenec",
"srpen", "září", "říjen", "listopad", "prosinec" };
// C#8
public static string GetCzechMonthName(byte month, byte @case = 1)