Issue
How can i simplify all this code. i wish to have one function perform the task below.
should be a simple task i am just fulfilling in more text here as stackoverflow demands more text. Please try to resolve thanks so much! typescript is an awesome language. its a little more different than javascript. when i attempted my own method for trying to resolve the below i got undefined...its hard trying to figure out how to group, target and change the values
class foods {
private apple: boolean;
private banana: boolean;
private guava: boolean;
private passionfruit: boolean;
private melon: boolean;
private oranges: boolean;
private porkchop: boolean;
private steak: boolean;
private chicken: boolean;
toggleApple() {
this.apple = true;
this.banana = false;
this.guava = false;
this.passionfruit = false;
this.melon = false;
this.oranges = false;
}
toogleBanana() {
this.apple = false;
this.banana = true;
this.guava = false;
this.passionfruit = false;
this.melon = false;
this.oranges = false;
}
toggleGuava() {
this.apple = false;
this.banana = false;
this.guava = true;
this.passionfruit = false;
this.melon = false;
this.oranges = false;
}
togglePassionFruit() {
this.apple = false;
this.banana = false;
this.guava = false;
this.passionfruit = true;
this.melon = false;
this.oranges = false;
}
toggleMelon() {
this.apple = false;
this.banana = false;
this.guava = false;
this.passionfruit = false;
this.melon = true;
this.oranges = false;
}
toggleOranges() {
this.apple = false;
this.banana = false;
this.guava = false;
this.passionfruit = false;
this.melon = false;
this.oranges = true;
}
}
Solution
You can allocate everything into a single function. I'm sure there would be much more creative solutions, though this solution would at least put all the logic into a single toggle function.
apple: boolean;
banana: boolean;
guava: boolean;
passionfruit: boolean;
melon: boolean;
oranges: boolean;
porkchop: boolean;
steak: boolean;
chicken: boolean;
constructor(
) {
this.apple = false;
this.banana = false;
this.guava = false;
this.passionfruit = false;
this.melon = false;
this.oranges = false;
}
toggleFruit(fruitName: string) {
(fruitName === 'apple' ? this.apple = true : this.apple = false);
(fruitName === 'banana' ? this.banana = true : this.banana = false);
(fruitName === 'guava' ? this.guava = true : this.guava = false);
(fruitName === 'passionfruit' ? this.passionfruit = true : this.passionfruit = false);
(fruitName === 'melon' ? this.melon = true : this.melon = false);
(fruitName === 'oranges' ? this.oranges = true : this.oranges = false);
}
Answered By - ReturnTable
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.