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 / 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 / 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 / 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 / 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 / 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 / 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 / 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("&")