Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
Cross-Tab State Sync with BroadcastChannel
Synchronize lightweight UI state between tabs from the same origin.
const channel = new BroadcastChannel('app-preferences');
const preferences = {
theme: 'dark',
compactMode: true,
};
channel.addEventListener('message', (event) => {
if (event.data?.type !== 'preferences-updated') {
return;
}
Promise-Based IndexedDB Key-Value Store
Store structured values in IndexedDB with a small promise-based wrapper.
const databaseName = 'app-cache';
const storeName = 'key-value';
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(databaseName, 1);
Web Worker for CPU-Heavy Calculations
Move expensive calculations off the main thread and return the result with postMessage.
// statistics.worker.js
self.addEventListener('message', (event) => {
const numbers = event.data;
const total = numbers.reduce(
(sum, value) => sum + value,
0,
);
self.postMessage({
total,
average: numbers.length
Infinite Scroll with IntersectionObserver
Load the next page when a sentinel approaches the viewport and prevent duplicate requests.
const sentinel = document.querySelector('[data-load-more]');
let page = 1;
let isLoading = false;
let hasMore = true;
const observer = new IntersectionObserver(
async (entries) => {
const entry = entries[0];
URLSearchParams Filter State
Read, update, and remove page filters without manually concatenating query strings.
function updateFilters(changes) {
const url = new URL(window.location.href);
Object.entries(changes).forEach(([key, value]) => {
const normalizedValue = String(value ?? '').trim();
if (normalizedValue === '') {
url.searchParams.delete(key);
Reusable useDebouncedValue Hook
Delay a rapidly changing value before triggering searches, validation, or API requests.
'use client';
import { useEffect, useState } from 'react';
export function useDebouncedValue<T>(
value: T,
delay = 300,
): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
Create Multiple Folders
A small Windows CMD snippet for creating several project folders at once.
@echo off
mkdir src
mkdir public
mkdir assets
mkdir assets\css
mkdir assets\js
mkdir assets\img
echo Project folders created.
pause
Group Array Items by Key
A useful PHP helper for grouping database rows by a selected key.
<?php
function groupByKey(array $items, string $key): array
{
$groups = [];
foreach ($items as $item) {
$groupKey = (string) ($item[$key] ?? '');
if ($groupKey === '') {
continue;
}
Simple Slug Generator
A compact PHP slug generator for URLs and filenames.
<?php
function makeSlug(string $text): string
{
$text = strtolower(trim($text));
$text = preg_replace('/[^a-z0-9]+/i', '-', $text);
$text = trim((string) $text, '-');
return $text !== '' ? $text : 'item';
}
Save and Load JSON from localStorage
A safe small helper for storing JSON data in localStorage.
function saveJson(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function loadJson(key, fallback = null) {
try {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : fallback;
} catch (error) {
Debounce Function
A reusable debounce helper for search inputs and resize handlers.
function debounce(callback, delay = 300) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
callback.apply(this, args);
}, delay);
};
}
const handleSearch = debounce((event) => {
Copy Text to Clipboard
A vanilla JavaScript helper to copy text to the clipboard with a fallback message.
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Copied to clipboard');
return true;
} catch (error) {
console.error('Clipboard copy failed:', error);
return false;
}
}
Fade In Utility Class
A reusable CSS fade-in animation utility class.
.fade-in {
animation: fade-in 300ms ease both;
}
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(6px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
CSS Loading Spinner
A small pure CSS loading spinner using border animation.
.spinner {
width: 40px;
height: 40px;
border: 4px solid #e5e7eb;
border-top-color: #4f46e5;
border-radius: 50%;
animation: spin 0.75s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
Basic Haskell Math and Utility Functions
Defines several mathematical and utility functions in Haskell including calculations for circle area, sphere volume, temperature conversion,...
module Gyak04 where
import Data.Char(toLower, toUpper, isLower, isUpper)
circleArea :: Double -> Double
circleArea r = (r^2)*pi
sphereVolume :: Double -> Double
sphereVolume r = 4*(r^3)*pi/3
cToF :: Double -> Double