Code Explainers

Code explainers tagged #closures

rust
use std::{collections::HashSet, sync::Arc};
 
use axum::{
    body::Body,

Feature-flag middleware in Axum

middleware async shared-state
Advanced 7 steps
javascript
const FOCUSABLE = [
  'a[href]',
  'button:not([disabled])',
  'input:not([disabled])',

How to trap keyboard focus in a dialog

accessibility dom event-handling
Intermediate 8 steps
php
<?php
 
final class MarkdownParser
{

Building a small Markdown-to-HTML parser in PHP

state-machine parsing closures
Intermediate 10 steps
javascript
function initScrollSpy() {
  const links = Array.from(document.querySelectorAll('.nav a[href^="#"]'));
  const sections = links
    .map((link) => document.querySelector(link.getAttribute('href')))

Building a scroll spy with IntersectionObserver

intersectionobserver dom event-driven
Intermediate 7 steps
python
from typing import Callable, Dict, Type
 
 
class PluginRegistry:

A decorator-based plugin registry in Python

decorators registry pattern factory
Intermediate 9 steps
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 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
go
package handlers
 
import (
	"net/http"

Sparse fieldsets in a Gin handler

sparse-fieldsets query-parsing json-serialization
Intermediate 9 steps
python
import os
import shutil
import tempfile
from contextlib import contextmanager

Transactional file operations in Python

transactions rollback closures
Intermediate 8 steps
ruby
class Pipeline
  def initialize
    @middlewares = []
  end

Building a middleware pipeline in Ruby

closures middleware composition
Advanced 8 steps
php
<?php
 
namespace App\Providers;
 

Defining feature flags with Laravel Pennant

feature-flags service-provider config-driven
Intermediate 6 steps
typescript
type Handler = (event: KeyboardEvent) => void;
 
interface Binding {
  combo: string;

Building a keyboard shortcut manager in TypeScript

event-handling normalization closures
Intermediate 7 steps
go
package config
 
import "time"
 

The functional options pattern in Go

functional-options closures immutability
Intermediate 7 steps
typescript
type AsyncMethod = (...args: any[]) => Promise<any>;
 
function LogExecutionTime(thresholdMs = 0) {
  return function <T extends AsyncMethod>(

A method decorator that times async calls

decorators higher-order-functions async
Advanced 9 steps
php
<?php
 
namespace App\Queue;
 

A stable priority job queue in PHP

priority-queue data-structures closures
Intermediate 8 steps