Published: October 26, 2022 • Updated: January 03, 2023 • 2 min read
Today I completed the ‘Resistor Color Trio’ TypeScript exercise on Exercism. This exercise asks us to write a TypeScript function that takes two color names (e.g. ‘brown’ and ‘black’) and a power-of-ten multiplier color (e.g. ‘black’), returning the electrical resistance they would produce in string format (‘10 ohms’ in this example).
Here’s the provided 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 = [
"black",
"brown",
"red",
"orange",
"yellow",
"green",
"blue",
"violet",
"grey",
"white"
];
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}`
};
Here are some notes on my solution.
decodedResistorValue
, but didn’t on my
duo solution. Probably different compiler versions.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.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.
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.