Skip to content

Instantly share code, notes, and snippets.

type Nullable<T> = T | undefined | null;
function isDefined<T>(item: T): item is NonNullable<T> {
return item !== undefined && item !== null;
}
function compact<T, R>(
list: Nullable<T[]>,
mapFn: (item: NonNullable<T>) => Nullable<R>
): R[] {
@toky-nomena
toky-nomena / sort.ts
Last active September 18, 2024 18:13
function filterFn<T>(element: T | undefined): element is T {
return element !== undefined;
}
function sortMessagesByBindings(messages: (Message | null | undefined)[], bindings: string[]): Message[] {
// Helper function to get the last component of a string
const getLastComponent = (str: string): string => {
const parts = str.split('.');
return parts[parts.length - 1] || '';
};
import React, { useState, useEffect, useTransition } from 'react';
import { useQuery, useQueryClient, QueryFunction } from 'react-query';
import axios, { AxiosError } from 'axios';
import Select from 'react-select';
interface Option {
value: string;
label: string;
}
type Predicate<T> = (result: T) => boolean;
interface RetryOptions {
retries: number;
delay?: number; // optional delay between retries in milliseconds
}
async function retryPromise<T>(
promiseFactory: () => Promise<T>,
predicate: Predicate<T>,
export const matcher = <Input, Output>(value: Input) => {
type Result = (value: Input) => Output;
type Expression = (value: Input) => boolean;
interface MatchCases {
expression: Expression;
result: Result;
}
const cases: MatchCases[] = [];
function isLeapYear(year: number): boolean {
return (year % 400 === 0) || (year % 100 !== 0 && year % 4 === 0);
}
type Join<K, P> = K extends string | number ?
P extends string | number ?
`${K}${"" extends P ? "" : "."}${P}`
: never : never;
type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...0[]]
type Paths<T, D extends number = 10> = [D] extends [never] ? never : T extends object ?
{ [K in keyof T]-?: K extends string | number ?`${K}` | Join<K, Paths<T[K], Prev[D]>> : never }[keyof T] : ""
function transformToSnakeCase(input: string): string {
return input
.replace(/([a-z])([A-Z])/g, '$1_$2') // Insert underscore between lowercase and uppercase letters
.replace(/([0-9]+)([a-zA-Z])/g, '$1_$2') // Insert underscore between digits and letters
.replace(/([a-zA-Z])([0-9]+)/g, '$1_$2') // Insert underscore between letters and digits
.toUpperCase(); // Convert the result to uppercase
}
const enum LogLevel {
Info = 'info',
Warning = 'warning',
Error = 'error',
}
class Logger {
private static logStyle = {
info: 'color: #3498db; font-weight: bold;',
warning: 'color: #f39c12; font-weight: bold;',
function error(message: string): never {
throw new Error(message)
}