Jake Worth

Resistor Color Trio in TypeScript

Published: October 26, 2022 2 min read

  • typescript

Today as a code kata I completed the ‘Resistor Color Trio’ TypeScript exercise on Exercism. Here’s my work.

This exercise asks us to write a TypeScript function that takes two color names (‘brown’ and ‘black’) and a power-of-ten multiplier color (‘black’), returning the electrical resistance they would produce (‘10 ohms’ in this example).


Here’s the unit test:

import { decodedResistorValue } from './resistor-color-trio'

describe('Resistor Colors', () => {
  it('Orange and orange and black', () => {
    expect(decodedResistorValue(['orange', 'orange', 'black'])).toEqual(
      '33 ohms'

  it('Blue and grey and brown', () => {
    expect(decodedResistorValue(['blue', 'grey', 'brown'])).toEqual('680 ohms')

  it('Red and black and red', () => {
    expect(decodedResistorValue(['red', 'black', 'red'])).toEqual('2 kiloohms')

  it('Green and brown and orange', () => {
    expect(decodedResistorValue(['green', 'brown', 'orange'])).toEqual(
      '51 kiloohms'

  it('Yellow and violet and yellow', () => {
    expect(decodedResistorValue(['yellow', 'violet', 'yellow'])).toEqual(
      '470 kiloohms'

And my solution:

const colorMap = [

export const decodedResistorValue = ([first, second, zeros]: Array<string>): string => {
  const baseValue = `${colorMap.indexOf(first)}${colorMap.indexOf(second)}`

  let value = Number(baseValue) * 10 ** colorMap.indexOf(zeros)
  let unit = 'ohms'
  if(value >= 1000) {
    value /= 1000
    unit = `kilo${unit}`

  return `${value} ${unit}`


Notes on my solution.

  • Once again, I’ve used implicit types. I’m not sure why this time the transpiler wanted to know the return type of decodedResistorValue, but didn’t on my duo exercise.
  • I chose to interpolate the base value rather than iterate to produce it, as I did on the duo exercise. I know more about the domain now than I did then.
  • There’s a lot of string interpolation here. I prefer that to concatenation, but it’s ugly.
  • I reassign unit and value when value is greater than 1K. Reassignment is a technique I try to avoid but sometimes I think it’s easier to read than the alternatives.
  • If there’s a unit of measurement bigger than kiloohms, this won’t scale to include that unit.

I’m doing these exercises because I’m bullish on TypeScript! I write TypeScript more slowly than JavaScript, but once I’ve handled the types, it becomes boring, highly predictable code.

Thank you Exercism maintainers for this exercise.

✉️ Get better at programming by learning with me. Subscribe to Jake Worth's Newsletter for bi-weekly ideas, creations, and curated resources from across the world of programming. Join me today!

Blog of Jake Worth, software engineer in Maine.

© 2022 Jake Worth.