Code Explainers

Code explainers tagged #encapsulation

typescript
interface RunningStats {
  count: number;
  total: number;
  average: number;

Streaming running averages in TypeScript

generators streaming incremental-aggregation
Intermediate 6 steps
ruby
class ProgressBar
  BAR_WIDTH = 40
 
  def initialize(total, io: $stdout)

Building a terminal progress bar in Ruby

state tracking terminal output time estimation
Intermediate 8 steps
rust
use rand::distributions::{Alphanumeric, DistString};
use rand::rngs::OsRng;
 
#[derive(Debug, Clone, PartialEq, Eq)]

A newtype wrapper for API tokens in Rust

newtype-pattern randomness encapsulation
Intermediate 6 steps
php
<?php
 
namespace App\Validation;
 

Building a reusable address form validator in PHP

validation error-accumulation regex
Intermediate 9 steps
ruby
require 'date'
require 'set'
 
class BusinessDayCalculator

Counting business days in Ruby

dates sets ranges
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
ruby
require "csv"
 
class CsvExporter
  def initialize(records, columns: nil)

Turning records into CSV in Ruby

csv data-export serialization
Intermediate 7 steps
ruby
require "phonelib"
 
class PhoneNumber
  class InvalidNumber < StandardError; end

Wrapping phone parsing in a Ruby value object

value-object memoization validation
Intermediate 7 steps
ruby
class PaymentGateway
  class MissingCredentialError < StandardError; end
 
  def initialize(env: Rails.env)

Wrapping Rails credentials in a gateway

encapsulation credentials error handling
Intermediate 6 steps
typescript
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { BullModule } from '@nestjs/bullmq';
 

How a NestJS feature module wires up

dependency-injection modularity orm
Intermediate 7 steps
ruby
class SignupValidator
  EMAIL_REGEX = /\A[^@\s]+@[^@\s]+\.[^@\s]+\z/
  MIN_PASSWORD_LENGTH = 8
 

Building a plain-Ruby signup validator

validation regex default-hash
Intermediate 7 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
php
<?php
 
namespace App\Support;
 

Locale-aware formatting with PHP's intl extension

internationalization encapsulation constructor-injection
Intermediate 7 steps
php
<?php
 
namespace App\View;
 

Building a safe HTML escaper in PHP

security xss escaping
Intermediate 6 steps
typescript
type CheckoutState = "cart" | "shipping" | "payment" | "review" | "confirmed";
 
type CheckoutEvent =
  | { type: "PROCEED" }

A typed checkout state machine in TypeScript

state-machine union-types type-safety
Intermediate 7 steps
ruby
class CheckoutService
  Result = Struct.new(:success?, :order, :error, keyword_init: true)
 
  def self.call(...)

How a Rails checkout service object works

service object transactions result object
Intermediate 9 steps
javascript
class Stack {
  #items = [];
 
  push(value) {

Building a Stack with private fields

data-structures encapsulation iterators
Intermediate 7 steps
php
<?php
 
class Entity
{

PHP magic methods for dynamic attributes

magic-methods overloading encapsulation
Intermediate 6 steps