Code Explainers

Code explainers tagged #closures

typescript
type EventMap = Record<string, unknown>;
 
type Handler<T> = (payload: T) => void;
 

A type-safe event bus in TypeScript

generics event-emitter type-safety
Advanced 7 steps
go
package middleware
 
import (
	"crypto/subtle"

Building an API-key middleware in Gin

middleware authentication dependency-injection
Intermediate 5 steps
javascript
class EventEmitter {
  constructor() {
    this.listeners = new Map();
  }

Building an EventEmitter in JavaScript

pub-sub closures map
Intermediate 7 steps
go
package web
 
import (
	"embed"

Serving embedded static assets in Go

embed static-assets http-handler
Intermediate 8 steps
javascript
function createCountdownTimer(durationSeconds, { onTick, onComplete } = {}) {
  let remaining = durationSeconds;
  let intervalId = null;
 

Building a countdown timer with closures

closures factory-function timers
Intermediate 9 steps
javascript
const crypto = require('crypto');
 
function securityHeaders(options = {}) {
  const {

A configurable security-headers middleware in Express

middleware http-headers content-security-policy
Intermediate 7 steps
javascript
const cache = new Map();
const inflight = new Map();
 
async function fetchResults(query) {

Building a typeahead with an LRU cache

caching lru-eviction request-deduplication
Intermediate 9 steps
javascript
export function createSearchClient(baseUrl) {
  let inFlight = null;
 
  async function search(query, { signal } = {}) {

Cancelling stale requests in a search client

closures abortcontroller async
Intermediate 8 steps
go
package middleware
 
import (
	"time"

Building a request logger middleware in Gin

middleware structured-logging closures
Intermediate 6 steps
go
package auth
 
import (
	"net/http"

Building a JWT auth middleware in Gin

middleware jwt authentication
Intermediate 7 steps
go
package server
 
import (
	"context"

Composing HTTP middleware in Go

middleware http-handlers closures
Intermediate 8 steps
ruby
def build_tree(rows, root_id: nil)
  children_by_parent = Hash.new { |hash, key| hash[key] = [] }
 
  rows.each do |row|

Building a tree from flat rows in Ruby

recursion hash-grouping tree-structure
Intermediate 5 steps
php
<?php
 
namespace App\Http\Controllers;
 

Building a filtered product index in Laravel

query-builder validation conditional-queries
Intermediate 9 steps
php
<?php
 
namespace App\Support;
 

Retry with exponential backoff in PHP

retry exponential-backoff error-handling
Intermediate 7 steps
python
import time
from dataclasses import dataclass, field
 
from fastapi import Depends, FastAPI, HTTPException, Request, status

Token-bucket rate limiting in FastAPI

rate-limiting token-bucket dependency-injection
Advanced 10 steps
php
function memoize(callable $fn): callable
{
    $cache = [];
 

How memoization works in PHP closures

memoization closures higher-order-functions
Intermediate 8 steps
javascript
const RATE_LIMIT = 100;
const WINDOW_MS = 60 * 1000;
const BLOCK_MS = 5 * 60 * 1000;
 

Building a rate-limiting middleware in Express

rate-limiting middleware closures
Intermediate 9 steps
rust
use std::collections::HashMap;
 
pub struct Memoizer<K, V, F> {
    cache: HashMap<K, V>,

A generic memoizer in Rust

memoization generics caching
Intermediate 6 steps