Solving Exercism's Resistor Color Trio in TypeScript
- 2 minutes read - 370 wordsToday I completed the ‘Resistor Color Trio’ TypeScript exercise on Exercism. Here’s my solution.
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).
My Solution
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}`
};
Notes
Here are some 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 solution. Probably different compiler versions. - 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 think that is more readable than string than string concatenation, but it’s ugly.
- I reassign
unit
andvalue
whenvalue
is greater than 1K. Reassignment is a technique I try to avoid but sometimes I think it’s easier to read than the alternatives. - This solution doesn’t scale to units bigger than kiloohms.
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.