Code Explainers

Code explainers tagged #closures

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
typescript
function throttle<T extends (...args: any[]) => void>(
  fn: T,
  limit: number
): (...args: Parameters<T>) => void {

Building a trailing-edge throttle in TypeScript

throttling closures generics
Intermediate 7 steps
javascript
function makeReorderableList(listEl, onReorder) {
  let draggedItem = null;
 
  listEl.addEventListener('dragstart', (e) => {

Drag-to-reorder lists with the HTML5 drag API

drag-and-drop event-delegation dom-manipulation
Intermediate 8 steps
python
import random
import time
import logging
from functools import wraps

A retry decorator with exponential backoff

decorators retry exponential-backoff
Intermediate 6 steps
python
from functools import wraps
 
 
def memoize(func):

Building a memoize decorator in Python

decorators closures memoization
Intermediate 5 steps
php
<?php
 
namespace App\Support;
 

Grouping records with array_reduce in PHP

array-reduce grouping higher-order-functions
Intermediate 6 steps
ruby
class EventEmitter
  def initialize
    @listeners = Hash.new { |hash, key| hash[key] = [] }
  end

Building an EventEmitter in Ruby

pub-sub closures callbacks
Intermediate 7 steps
ruby
# Curry a multi-argument lambda so it can be applied one argument at a time.
add = ->(a, b, c) { a + b + c }
 
# Proc#curry returns a curried version that collects arguments incrementally.

Currying lambdas and methods in Ruby

currying closures partial-application
Intermediate 7 steps
go
package middleware
 
import (
	"net/http"

Building a bearer-token auth middleware in Gin

middleware authentication closures
Intermediate 5 steps
javascript
function debounce(fn, delay) {
  let timeoutId = null;
 
  function debounced(...args) {

Building a debounce function in JavaScript

closures timers higher-order-functions
Intermediate 6 steps
javascript
function throttle(fn, wait) {
  let lastCall = 0;
  let timeoutId = null;
  let lastArgs = null;

Building a leading-and-trailing throttle

closures rate-limiting timers
Advanced 6 steps
javascript
function delegate(root, eventType, selector, handler) {
  const listener = (event) => {
    let node = event.target;
    while (node && node !== root) {

Event delegation with a clean teardown

event-delegation dom closures
Intermediate 8 steps