Skip to content

Instantly share code, notes, and snippets.

View tolotrasmile's full-sized avatar
🏆
Positive mindset

Tolotra Raharison tolotrasmile

🏆
Positive mindset
View GitHub Profile
/**
* Generate random string with specified length
* Each generated letter will be from A to Z
*
* 65 = A
* 90 = Z
* A-Z = 25
*
* @param length
*/
export const enum PadOrder {
Ascending,
Descending,
}
export function pad(
value: string,
paddingChar: string,
totalLength: number,
accumulator: (p: string, v: string) => string
import type { RestApi } from './RestApi'
/**
* Immutable fluent fetch API
*
* @param baseUrl
* @param urls
* @param headers
* @param params
*/
export interface RestApi {
url(url: string): this
post(body?: BodyInit | null): Promise<Response>
get(): Promise<Response>
auth(value: string): this
headers(key: string, value: string): this
import { Dispatch, useMemo, useReducer } from 'react'
// useStateReducer action type
type ActionType<S> = Partial<S> | ((params: S) => Partial<S>)
// useStateReducer reducer type
type Reducer<S> = (state: S, action: ActionType<S>) => S
// Default reducer. Override the old value with the action
export function stateReducer<S>(state: S, action: ActionType<S>): S {
type FetchParams = Parameters<typeof fetch>
type FetchReturn = ReturnType<typeof fetch>
export function fetchRetry(
input: FetchParams[0],
init?: FetchParams[1],
retry: number = 0,
delayMs: number = 1000
): FetchReturn {
return fetch(input, init).catch(error => {
// eslint-disable-next-line
export type Prettify<T> = { [K in keyof T]: T[K] } & {}
// https://github.com/total-typescript/shoehorn
export type NoInfer<T> = [T][T extends any ? 0 : never];
export type DeepPartial<T> = T extends (...args: any[]) => unknown
? T | undefined
: T extends object
? T extends ReadonlyArray<infer ItemType>
? ItemType[] extends T
? readonly ItemType[] extends T
? ReadonlyArray<DeepPartial<ItemType | undefined>>
: Array<DeepPartial<ItemType | undefined>>
function groupBy<T extends Record<string, unknown>, K extends keyof T>(array: T[], key: K): Record<T[K] & PropertyKey, T[]> {
return array.reduce((result, current) => {
const currentKey = current[key] as T[K] & PropertyKey
if (Array.isArray(result[currentKey])) {
result[currentKey].push(current)
} else {
result[currentKey] = [current]
}
return result
}, {} as Record<T[K] & PropertyKey, T[]>)
function range(start: number, end: number, step = 1) {
return {
[Symbol.iterator]() {
return this
},
next() {
if (start < end) {
start = start + step
return {
value: start,