Skip to content

Instantly share code, notes, and snippets.

View smitroshin's full-sized avatar

Serghei Mitroșin smitroshin

  • Amdaris
  • Chisinau, Moldova
View GitHub Profile
@smitroshin
smitroshin / encodeArrayToQueryParam.ts
Created December 8, 2024 10:12
Encode an array of strings into query param
/**
* Encode an array of strings into query param
*
* Format: repetitive params
*
* Example: `encodeArrayToQueryParam("param", ["a", "b", "c"])` => `"param=a&param=b&param=c"`
*/
export const encodeArrayToQueryParam = (key: string, array: string[]) =>
array.map((item) => `${encodeURIComponent(key)}=${encodeURIComponent(item)}`).join("&")
@smitroshin
smitroshin / useIIFE.ts
Created August 14, 2024 17:42
useIIFE
export const useIIFE = <T>(callback: () => T) => {
return iife(callback);
};
const iife = <T extends (...args: any[]) => any>(callback: T): ReturnType<T> => callback();
@smitroshin
smitroshin / componentWithSubComponents.js
Created August 14, 2024 14:45
Export a component with sub-components
export default Object.assign(Header, {
Title: HeaderTitle,
Subtitle: HeaderSubtitle,
})
@smitroshin
smitroshin / useSafeTimeout.ts
Created July 14, 2024 11:23
A normal setTimeout with automatic cleanup on unmount
import { useCallback, useEffect, useRef } from "react"
/**
* A normal setTimeout with automatic cleanup on unmount
*/
export const useSafeTimeout = () => {
const timeout = useRef<NodeJS.Timeout | null>(null)
const setSafeTimeout = useCallback((callback: () => void, ms: number) => {
timeout.current = setTimeout(callback, ms)
@smitroshin
smitroshin / useStatefulRef.ts
Last active November 27, 2023 18:22
React hook - useStatefulRef
import { useState } from "react";
/**
* As an API it's the same useRef,
* but it uses useState under the hood.
*
* Used to watch the ref changing between re-renders.
*
* Source: https://non-traditional.dev/creating-a-stateful-ref-object-in-react-fcd56d9dea58
*/
@smitroshin
smitroshin / useDebouncedWindowResize.ts
Last active November 21, 2023 13:20
React hook - useDebouncedWindowResize
import { useState } from "react";
import { useMount, usePrevious, useToggle } from "react-use";
export function debounce(func: Function, timeout = 300) {
let timer: any;
return (...args: any[]) => {
clearTimeout(timer);
timer = setTimeout(() => {
func(...args);
}, timeout);
@smitroshin
smitroshin / getPdfPageCount.ts
Created November 15, 2023 12:58
Get PDF page count from a PDF Blob
/**
* Get PDF page count from a PDF Blob
*
* Source: https://stackoverflow.com/a/58089003
*/
export const getPdfPageCount = (pdfFile: Blob) =>
new Promise<number>((resolve, reject) => {
const reader = new FileReader();
reader.readAsBinaryString(pdfFile);
@smitroshin
smitroshin / axiosAsyncHelper.ts
Last active August 30, 2023 08:48
Async + Await Error Handling Strategy using Axios
import { AxiosError, AxiosResponse } from "axios";
/**
* Axios types overload
*/
export function asyncHelper<ResponseType = any, ErrorType = any>(
promise: Promise<AxiosResponse<ResponseType | ErrorType, any>> | null | undefined | false
): Promise<{ response: AxiosResponse<ResponseType> | null; error: AxiosError<ErrorType> | null }>;
/**
@smitroshin
smitroshin / pxToRem.ts
Created July 12, 2023 15:10
Convert "px" to "rem"
/**
* Assuming 1rem = 16px
*
* 14 => 0.875
*/
export const pxToRem = (val: number, htmlFontSize?: number) => val / (htmlFontSize ?? 16);
/**
* Assuming 1rem = 16px
*
@smitroshin
smitroshin / toKebabCase.ts
Created June 26, 2023 14:30
Convert a text to kebab-case format
/**
* Convert a text to kebab-case format
*/
export const toKebabCase = (text: string) =>
text
.trim()
.replace(/([a-z])([A-Z])/g, "$1-$2") // insert dash between lowercase and uppercase letters
.replace(/\s+/g, "-") // replace spaces with dashes
.toLowerCase(); // convert all characters to lowercase