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("")
)
}
}
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("")
)
}
}
Share
Improve this question
edited Jun 29, 2020 at 1:59
andreoss
asked Jun 29, 2020 at 1:49
andreossandreoss
1,8201 gold badge12 silver badges29 bronze badges
2
- That's what you're doing already? – zerkms Commented Jun 29, 2020 at 1:54
-
@zerkms I use an auxilary field as mapping function, I'd rather prefer something like
.map(x => Lookup[x])
– andreoss Commented Jun 29, 2020 at 1:58
2 Answers
Reset to default 7It'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 piler can get grumpy about this kind of thing. You may need to do something like this to make the piler 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!
Further to - and based on - Justin's answer, here's another example around where to define your types:
const messages: {[index: string]: string} = {
'required': 'The value is required',
'minimumValue': 'The value is not large enough'
}
const validationErrorType = 'required';
const messageToUser = messages[validationErrorType];