Code Explainers

Code explainers tagged #lookup-table

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
ruby
class ImageNormalizer
  ORIENTATION_TRANSFORMS = {
    1 => ->(img) {},
    2 => ->(img) { img.flop },

Correcting EXIF orientation in Ruby

lookup-table lambdas image-processing
Intermediate 7 steps
python
from datetime import datetime, timezone
 
_INTERVALS = (
    ("year", 60 * 60 * 24 * 365),

Building a human-friendly time_ago helper

datetime timezones formatting
Intermediate 5 steps
go
package humanize
 
import (
	"fmt"

Parsing human-readable byte sizes in Go

parsing regex lookup-table
Intermediate 8 steps
rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
    Png,
    Jpeg,

Detecting file types by magic bytes in Rust

pattern-matching byte-slices lookup-table
Intermediate 7 steps
typescript
const ISO_DURATION = /^P(?:(\d+(?:\.\d+)?)Y)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)W)?(?:(\d+(?:\.\d+)?)D)?(?:T(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?)?$/;
 
const SECONDS_PER = {
  years: 365 * 24 * 60 * 60,

Parsing ISO 8601 durations to seconds

regex parsing iso-8601
Intermediate 7 steps
ruby
class DurationParser
  UNIT_SECONDS = {
    'w' => 604_800,
    'd' => 86_400,

Parsing duration strings into seconds in Ruby

parsing regular-expressions validation
Intermediate 7 steps
ruby
class ParamCoercer
  TYPES = {
    integer: ->(v) { Integer(v) },
    float:   ->(v) { Float(v) },

Coercing request params by schema in Ruby

lambdas type-coercion lookup-table
Intermediate 7 steps
javascript
const DIVISIONS = [
  { amount: 60, unit: 'seconds' },
  { amount: 60, unit: 'minutes' },
  { amount: 24, unit: 'hours' },

Building a human-friendly timeAgo formatter

internationalization relative-time lookup-table
Intermediate 6 steps
typescript
const DIVISIONS: { amount: number; unit: Intl.RelativeTimeFormatUnit }[] = [
  { amount: 60, unit: "seconds" },
  { amount: 60, unit: "minutes" },
  { amount: 24, unit: "hours" },

Human-readable relative times with Intl

internationalization date-formatting lookup-table
Intermediate 7 steps