Back to Morse Tree
SOURCE / PINNED RELEASE

Made of little things.

Morse Tree

Release
52c388d28ec3…
Author-recorded commit
fd8192a198f7…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-6ab5aa84ba1

Archive hash verified: 9d22ca7f5a712965…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/morse.ts
// International Morse code for the 26 letters. Every code is at most four
// symbols long, so the letters fill a binary tree of depth four: a dot moves
// to the left child, a dash to the right child.

export const LETTER_CODES: Readonly<Record<string, string>> = {
  A: '.-', B: '-...', C: '-.-.', D: '-..', E: '.', F: '..-.', G: '--.',
  H: '....', I: '..', J: '.---', K: '-.-', L: '.-..', M: '--', N: '-.',
  O: '---', P: '.--.', Q: '--.-', R: '.-.', S: '...', T: '-', U: '..-',
  V: '...-', W: '.--', X: '-..-', Y: '-.--', Z: '--..',
};

export const MAX_DEPTH = 4;

const CODE_LETTERS: Readonly<Record<string, string>> = Object.fromEntries(
  Object.entries(LETTER_CODES).map(([letter, code]) => [code, letter]),
);

/** The letter at a tree node, or null for the root and the four empty nodes. */
export function letterAt(code: string): string | null {
  return CODE_LETTERS[code] ?? null;
}

export function codeOf(letter: string): string | null {
  return LETTER_CODES[letter.toUpperCase()] ?? null;
}

/** Every node of the full binary tree, root first, breadth first. */
export function treeCodes(): string[] {
  const codes = [''];
  for (let depth = 1; depth <= MAX_DEPTH; depth += 1) {
    for (let index = 0; index < 2 ** depth; index += 1) {
      codes.push(codeAt(depth, index));
    }
  }
  return codes;
}

/** The root and the nodes that carry a letter: the tree without its four empty nodes. */
export function letterTreeCodes(): string[] {
  return treeCodes().filter((code) => code === '' || letterAt(code) !== null);
}

export function hasNode(code: string): boolean {
  return code === '' || letterAt(code) !== null;
}

/**
 * Horizontal slot of every node when the empty nodes take no room. Leaves get
 * one slot each from left to right; a parent sits between its two children, or
 * half a slot towards the missing side when it has only one, so the branch
 * still leans the way its symbol goes.
 */
export function treeSlots(): { slots: Map<string, number>; count: number } {
  const slots = new Map<string, number>();
  let next = 0;
  const visit = (code: string): number => {
    const dot = code.length < MAX_DEPTH && hasNode(code + '.') ? visit(code + '.') : null;
    const dash = code.length < MAX_DEPTH && hasNode(code + '-') ? visit(code + '-') : null;
    let slot: number;
    if (dot !== null && dash !== null) slot = (dot + dash) / 2;
    else if (dot !== null) slot = dot + 0.5;
    else if (dash !== null) slot = dash - 0.5;
    else slot = next++;
    slots.set(code, slot);
    return slot;
  };
  visit('');
  return { slots, count: next };
}

/** Node code from its depth and left-to-right index (dot = 0 bit, dash = 1 bit). */
export function codeAt(depth: number, index: number): string {
  let code = '';
  for (let bit = depth - 1; bit >= 0; bit -= 1) code += (index >> bit) & 1 ? '-' : '.';
  return code;
}

/** Left-to-right index of a node within its depth. */
export function indexOf(code: string): number {
  let index = 0;
  for (const symbol of code) index = index * 2 + (symbol === '-' ? 1 : 0);
  return index;
}

/** Duration of one dot in milliseconds at the PARIS standard. */
export function ditMs(wpm: number): number {
  return 1200 / wpm;
}

export interface Tone {
  /** Offset from the start in dot units. */
  start: number;
  /** Length in dot units: 1 for a dot, 3 for a dash. */
  length: number;
  /** Position of the symbol in its letter. */
  symbol: number;
  /** Position of the letter in the text. */
  letter: number;
}

/**
 * Timing of a text in dot units: one unit between symbols, three between
 * letters and seven between words. Characters without a code are skipped.
 */
export function schedule(text: string): { tones: Tone[]; length: number } {
  const tones: Tone[] = [];
  let at = 0;
  let pendingGap = 0;
  [...text].forEach((char, letter) => {
    if (char === ' ') {
      if (tones.length > 0) pendingGap = 7;
      return;
    }
    const code = codeOf(char);
    if (!code) return;
    at += pendingGap;
    [...code].forEach((symbol, index) => {
      if (index > 0) at += 1;
      const length = symbol === '-' ? 3 : 1;
      tones.push({ start: at, length, symbol: index, letter });
      at += length;
    });
    pendingGap = 3;
  });
  return { tones, length: at };
}

// Straight-key decoding. The ITU standard (ITU-R M.1677-1) fixes the ideal
// lengths: a dot is one unit, a dash three; the gap inside a letter is one
// unit, between letters three and between words seven. A receiver splits at
// the midpoints, which leaves the most room for an uneven hand.

/** Shortest press that counts at all: shorter is contact bounce, not keying. */
export const BOUNCE_MS = 15;
/** A press of two units or longer is a dash. */
export const DASH_FROM_UNITS = 2;
/** A silence of two units ends the letter. */
export const LETTER_GAP_UNITS = 2;
/** A silence of five units ends the word. */
export const WORD_GAP_UNITS = 5;

export type Mark = '.' | '-';

export function classifyMark(ms: number, unit: number): Mark | null {
  if (ms < BOUNCE_MS) return null;
  return ms < DASH_FROM_UNITS * unit ? '.' : '-';
}

export type Gap = 'symbol' | 'letter' | 'word';

export function classifyGap(ms: number, unit: number): Gap {
  if (ms < LETTER_GAP_UNITS * unit) return 'symbol';
  if (ms < WORD_GAP_UNITS * unit) return 'letter';
  return 'word';
}

/** Ideal length of a mark or gap in units. */
export function idealUnits(kind: Mark | Gap): number {
  return { '.': 1, '-': 3, symbol: 1, letter: 3, word: 7 }[kind];
}

/** How close a duration came to its ideal: 1 is exact, 0 is off by its own length or more. */
export function accuracy(ms: number, unit: number, kind: Mark | Gap): number {
  const ideal = idealUnits(kind) * unit;
  return Math.max(0, 1 - Math.abs(ms - ideal) / ideal);
}