Code Explainers

Code explainers tagged #reduce

javascript
const DISCOUNT_CODES = {
  SAVE10: { type: 'percent', value: 0.1 },
  WELCOME5: { type: 'fixed', value: 5 },
  FREESHIP: { type: 'shipping', value: Infinity },

How a cart total is calculated with discounts

reduce lookup-table options-object
Intermediate 8 steps
typescript
type Flatten = Record<string, unknown>;
 
function isPlainObject(value: unknown): value is Record<string, unknown> {
  return (

Flattening nested objects into dotted keys

recursion reduce type-guards
Intermediate 7 steps
ruby
class TemplateInterpolator
  PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/
 
  def initialize(strict: false)

Interpolating templates with dotted keys in Ruby

regex string-interpolation hash-traversal
Intermediate 6 steps
ruby
class Pipeline
  def initialize
    @middlewares = []
  end

Building a middleware pipeline in Ruby

closures middleware composition
Advanced 8 steps
python
from collections import ChainMap
from functools import reduce
from typing import Any, Iterable, Mapping
 

Five ways to merge dicts in Python

dictionaries merging recursion
Intermediate 8 steps
typescript
interface Order {
  id: number;
  customerId: string;
  total: number;

A type-safe groupBy in TypeScript

generics reduce type-inference
Intermediate 6 steps
javascript
function groupBy(items, keySelector) {
  const resolveKey = typeof keySelector === 'function'
    ? keySelector
    : (item) => item[keySelector];

Building a flexible groupBy in JavaScript

higher-order-functions reduce data-transformation
Intermediate 6 steps
javascript
function flatten(arr) {
  const result = [];
  for (const item of arr) {
    if (Array.isArray(item)) {

Flattening nested arrays with recursion

recursion arrays reduce
Intermediate 7 steps