How can I use a simple JavaScript lookup table (which is the mapping itself) inside map function?
I.e how can i get rid of this "code"
field (borrowed from here), and use only the lookup table inside map
method?
const Resistors = { "black": 0, "brown": 1, "red": 2, "orange": 3, "yellow": 4, "green": 5, "blue": 6, "violet": 7, "grey": 8, "white": 9, // Why not Resistors[color] "code" : (color: string) => { function valueOf<T, K extends keyof T>(obj: T, key: K) { return obj[key]; } return valueOf(Resistors, color as any); } } class ResistorColor { private colors: string[]; constructor(colors: string[]) { this.colors = colors; } value = () => { return Number.parseInt( this.colors .map(Resistors.code) // How can i get rid of .code here? .join("") ) } }
Advertisement
Answer
It’s a little hard to know exactly what you’re looking for, but at a glance … you can! You should be able to do:
const Resistors = { black: 0, brown: 1, }
And then…
const numericColorCode = Resistors['black']; console.log(numericColorCode) // should be 0
Now sometimes the TypeScript compiler can get grumpy about this kind of thing. You may need to do something like this to make the compiler happy:
const numericColorCode = (Resistors as {[index: string]: number})['black'];
As for your question below that – use Object.keys
and a Array.join
!
const allTheColors = Object.keys(Resistors).join(','); console.log(allTheColors); // should be 'black,brown'
Hope this helps!