Code Explainers

Javascript code explainers

javascript
const ROLE_PERMISSIONS = {
  admin: ['users:read', 'users:write', 'billing:read', 'billing:write'],
  manager: ['users:read', 'billing:read'],
  member: ['users:read'],

Role-based permissions middleware in Express

authorization middleware rbac
Intermediate 9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) {
  const formatter = new Intl.NumberFormat(locale);
  const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ',';
  const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';

Live thousand separators without losing the caret

dom intl caret-preservation
Advanced 8 steps
javascript
import { useReducer, useEffect } from "react";
 
const initialState = { status: "idle", data: null, error: null };
 

Building a data-fetching hook in React

custom-hooks usereducer data-fetching
Intermediate 9 steps
javascript
const express = require('express');
const app = express();
 
app.get('/health', (req, res) => res.json({ status: 'ok' }));

Graceful shutdown in an Express server

graceful-shutdown signal-handling connection-tracking
Advanced 9 steps
javascript
import { useState, useEffect, useCallback } from 'react';
 
function getColumnCount(width) {
  if (width < 640) return 1;

A responsive column hook in React

custom-hooks debouncing responsive-design
Intermediate 7 steps
javascript
function initCharacterCounter(textarea, options = {}) {
  const maxLength = options.maxLength ?? 280;
  const warnThreshold = options.warnThreshold ?? 0.9;
 

A live character counter for textareas

dom closures accessibility
Intermediate 7 steps
javascript
function autoResizeTextarea(textarea, { maxHeight = Infinity } = {}) {
  const resize = () => {
    textarea.style.height = 'auto';
    const contentHeight = textarea.scrollHeight;

Auto-resizing a textarea to fit its content

dom event-listener cleanup
Intermediate 7 steps
javascript
const zxcvbn = require('zxcvbn');
 
const STRENGTH_LABELS = ['Very weak', 'Weak', 'Fair', 'Strong', 'Very strong'];
const STRENGTH_COLORS = ['#d64545', '#e0803c', '#d9c94c', '#5aa84f', '#2f8f3a'];

Building a live password strength meter

debounce closures dom-events
Intermediate 8 steps
javascript
function usePagination(items, pageSize = 10) {
  let currentPage = 1;
  const totalPages = Math.max(1, Math.ceil(items.length / pageSize));
 

A closure-based pagination helper in JS

closures encapsulation factory-function
Intermediate 9 steps
javascript
const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
 
function coerce(value) {
  const trimmed = value.trim();

Parsing YAML-style frontmatter in JavaScript

parsing regular-expressions type-coercion
Intermediate 9 steps
javascript
const IDLE_TIMEOUT = 15 * 60 * 1000;
const WARNING_BEFORE = 60 * 1000;
const ACTIVITY_EVENTS = ['mousemove', 'keydown', 'scroll', 'touchstart', 'click'];
 

How an idle-session monitor logs you out

timers throttling broadcastchannel
Intermediate 8 steps
javascript
import { ImageResponse } from 'next/og'
 
export function manifest() {
  return {

Generating a PWA manifest and icon in Next.js

pwa metadata og-image
Intermediate 9 steps
javascript
function isValidCardNumber(input) {
  const digits = String(input).replace(/[\s-]/g, '');
 
  if (!/^\d{13,19}$/.test(digits)) {

Validating card numbers with Luhn

checksum validation luhn-algorithm
Intermediate 7 steps
javascript
import { useEffect, useState } from 'react';
 
export function useJobStatus(jobId, { interval = 3000 } = {}) {
  const [status, setStatus] = useState('pending');

Polling a job status with a React hook

custom-hooks polling cleanup
Intermediate 8 steps
javascript
const express = require('express');
const { AsyncLocalStorage } = require('async_hooks');
const { randomUUID } = require('crypto');
 

Per-request logging context in Express

async-local-storage middleware structured-logging
Advanced 8 steps
javascript
function useHashState(key, defaultValue) {
  const parse = () => {
    const params = new URLSearchParams(window.location.hash.slice(1));
    return params.has(key) ? params.get(key) : defaultValue;

A React hook backed by the URL hash

custom-hooks url-state event-listeners
Intermediate 6 steps
javascript
function hexToRgb(hex) {
  const normalized = hex.replace(/^#/, '');
  const full = normalized.length === 3
    ? normalized.split('').map((c) => c + c).join('')

Building a two-way color picker in JS

bitwise dom-events data-conversion
Intermediate 9 steps
javascript
import { useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
 
export function RouteFocus({ title, children }) {

Managing focus on route change in React

accessibility focus-management routing
Intermediate 6 steps