Jake Worth

Jake Worth

Solving Exercism's Resistor Color Duo in TypeScript

Published: October 24, 2022 • Updated: January 03, 2023 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 (e.g. ‘brown’ and ‘black’) and returns the electrical resistance they would produce on a resistor as a number (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 by index can feel like a magic number, whereas naming the two colors feels explicit.
  • I like anytime I get to use reduce.
  • Looking at other solutions, I think that I could have take a more mathematical approach instead of string manipulation. That’s not how I would write this in production so I think this is an honest effort for me.

I have also solved the trio version of this problem.


Get better at programming by learning with me. Subscribe to my newsletter for weekly ideas, creations, and curated resources from across the world of programming. Join me today!