Code Explainers

Code explainers tagged #lookup-table

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