Jake Worth

Resistor Color Duo in TypeScript

Published: October 24, 2022 2 min read

  • typescript

Today as a code kata I completed the ‘Resistor Color Duo’ 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 returns the electrical resistance they would produce on a resistor (10 in this example).

My Goals

I approached this challenge with the following goals:

  • Solve the problem
  • Learn TypeScript better
  • Leverage implicit typing

Here’s the spec and my solution.

Solution

Here’s spec that describes the desired behavior.

import { decodedValue } from './resistor-color-duo'

describe('Resistor Colors', () => {
  it('Brown and black', () => {
    expect(decodedValue(['brown', 'black'])).toEqual(10)
  })

  it('Blue and grey', () => {
    expect(decodedValue(['blue', 'grey'])).toEqual(68)
  })

  it('Yellow and violet', () => {
    expect(decodedValue(['yellow', 'violet'])).toEqual(47)
  })

  it('Orange and orange', () => {
    expect(decodedValue(['orange', 'orange'])).toEqual(33)
  })

  it('Ignore additional colors', () => {
    expect(decodedValue(['green', 'brown', 'orange'])).toEqual(51)
  })
})

And here’s my solution.

const resistances = [
  "black",
  "brown",
  "red",
  "orange",
  "yellow",
  "green",
  "blue",
  "violet",
  "grey",
  "white"
];

export const decodedValue = ([first, last]: Array<string>) => {
  const value = [first, last].reduce(
    (prev, color) => prev + resistances.indexOf(color),
    ""
  );

  return Number(value);
};

Notes

Notes on my solution.

  • I like that this solution uses implicit types. I only added types when the complier asked.
  • I like that this solution uses the coincidence that each color has a sequential resistance number that aligns with an array index.
  • I like that the function uses destructured arguments rather than slicing the array. Slicing can feel like a magic number, whereas naming the two colors feels explicit.
  • I like the I used reduce.
  • Looking at other solutions, I think that I could have take a more mathematical approach rather than string manipulation. That’s not how I would write this in production so I think this is an honest approach for me.

Thank you Exercism maintainers for this challenge.

✉️ 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.