Skip to main content

Snippets

Short, reusable bits of code I keep coming back to. Copy, paste, and adapt — nothing fancy, just stuff that earns its keep.

Center a div

The classic. Flexbox makes it boring, which is the goal.

css
.center {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

Prettify (TypeScript utility type)

Expands intersection types into a single flat object in your editor hover. Handy when you compose lots of types.

typescript
export type Prettify<T> = {
  [K in keyof T]: T[K]
} & {}

// Usage
type User = { id: string } & { name: string }
type Pretty = Prettify<User>
// Hover shows: { id: string; name: string }

Debounce (vanilla TS)

Tiny debounce helper with no dependencies — useful for search inputs and resize listeners.

typescript
export function debounce<T extends (...args: never[]) => unknown>(
  fn: T,
  delay = 300
): (...args: Parameters<T>) => void {
  let timer: ReturnType<typeof setTimeout> | null = null
  return (...args: Parameters<T>) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => fn(...args), delay)
  }
}

Copy to clipboard

Modern Clipboard API with a graceful fallback for older browsers and insecure contexts.

typescript
export async function copyToClipboard(text: string): Promise<boolean> {
  try {
    if (navigator?.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      return true
    }

    const textarea = document.createElement('textarea')
    textarea.value = text
    textarea.style.position = 'fixed'
    textarea.style.opacity = '0'
    document.body.appendChild(textarea)
    textarea.select()
    const ok = document.execCommand('copy')
    document.body.removeChild(textarea)
    return ok
  } catch {
    return false
  }
}