All files / web/src/lib/audio numberToClipIds.ts

100% Statements 54/54
100% Branches 17/17
100% Functions 1/1
100% Lines 54/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 551x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 44x 3x 3x 41x 44x 20x 20x 21x 21x 21x 21x 21x 44x 7x 7x 7x 21x 21x 21x 44x 10x 10x 10x 21x 21x 21x 44x 5x 44x 5x 16x 11x 11x 11x 11x 10x 10x 11x 21x 21x 21x  
/**
 * Convert a number (0-9999) to an array of clip IDs.
 *
 * Parallel to `numberToEnglish` but returns clip ID strings
 * that map to entries in `clips/numbers.ts`.
 *
 * Examples:
 *   numberToClipIds(5)    → ['number-5']
 *   numberToClipIds(42)   → ['number-40', 'number-2']
 *   numberToClipIds(157)  → ['number-1', 'number-hundred', 'number-50', 'number-7']
 *   numberToClipIds(2000) → ['number-2', 'number-thousand']
 */
export function numberToClipIds(n: number): string[] {
  if (n < 0 || n > 9999 || !Number.isInteger(n)) {
    throw new Error(`numberToClipIds: expected integer 0-9999, got ${n}`)
  }
 
  if (n <= 20) {
    return [`number-${n}`]
  }
 
  const clips: string[] = []
 
  // Thousands
  const thousands = Math.floor(n / 1000)
  if (thousands > 0) {
    clips.push(`number-${thousands}`)
    clips.push('number-thousand')
  }
 
  // Hundreds
  const hundreds = Math.floor((n % 1000) / 100)
  if (hundreds > 0) {
    clips.push(`number-${hundreds}`)
    clips.push('number-hundred')
  }
 
  // Remainder (0-99)
  const remainder = n % 100
  if (remainder === 0) {
    // Nothing to add
  } else if (remainder <= 20) {
    clips.push(`number-${remainder}`)
  } else {
    const tens = Math.floor(remainder / 10)
    const ones = remainder % 10
    clips.push(`number-${tens * 10}`)
    if (ones > 0) {
      clips.push(`number-${ones}`)
    }
  }
 
  return clips
}