Skip to content

Instantly share code, notes, and snippets.

@graynun
Last active July 27, 2020 11:36
Show Gist options
  • Save graynun/53c1b14f7acc9f0d905ab07cb54144c7 to your computer and use it in GitHub Desktop.
Save graynun/53c1b14f7acc9f0d905ab07cb54144c7 to your computer and use it in GitHub Desktop.
Replace Conditional with Polymorphism
function plumages(birds) {
return new Map(birds
.map(b => creaetBird(b))
.map(bird => [bird.name, b.plumage])
);
}
function speeds(birds) {
return new Map(birds
.map(b => creaetBird(b))
.map(bird => [bird.name, bird.airSpeedVelocity])
);
}
function creaetBird(bird) {
switch (bird.type) {
case '유럽 제비':
return new EurpoeanSwallow(bird);
case '아프리카 제비':
return new AfricanSwallow(bird);
case '노르웨이 파랑 앵무':
return new NorwegianBlueParrot(bird);
default:
return new Bird(bird);
}
}
class EurpoeanSwallow extends Bird {
get plumage() {
return "보통이다";
}
get airSpeedVelocity() {
return 35;
}
}
class AfricanSwallow extends Bird {
get plumage() {
return (bird.numberOfCoconuts > 2) ? "지쳤다" : "보통이다";
}
get airSpeedVelocity() {
return 40 - 2 * bird.numberOfCoconuts;
}
}
class NorwegianBlueParrot extends Bird {
get plumage() {
return (bird.voltage > 100) ? "그을렸다" : "예쁘다";
}
get airSpeedVelocity() {
return (bird.isNailed) ? 0 : 10 + bird.voltage / 10;
}
}
class Bird {
constructor(birdObject) {
Object.assign(this, birdObject);
}
get plumage() {
return "알 수 없다";
}
get airSpeedVelocity() {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment