Published: October 24, 2022 • Updated: January 03, 2023 • 2 min read
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).
I approached this challenge with the following goals:
Here’s the spec and my 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 on my solution.
reduce
.I have also solved the trio version of this problem.
What are your thoughts on this? Let me know!
Join 100+ engineers who subscribe for advice, commentary, and technical deep-dives into the world of software.