Skip to content

Instantly share code, notes, and snippets.

@osamaAbdullah
Created September 9, 2020 21:41
Show Gist options
  • Save osamaAbdullah/8aaa98d0740211554d6334744c4de5f8 to your computer and use it in GitHub Desktop.
Save osamaAbdullah/8aaa98d0740211554d6334744c4de5f8 to your computer and use it in GitHub Desktop.
composition in js
function walker({name}) {
return {
walk: () => console.log(name + ' can walk'),
}
}
function attacker({name}) {
return {
attack: () => console.log(name + ' can attack'),
}
}
function swimmer({name}) {
return {
swim: () => console.log(name + ' can swim'),
}
}
function flyer({name}) {
return {
fly: () => console.log(name + ' can fly'),
}
}
function monster(name) {
return {
...walker({name}),
...attacker({name}),
}
}
function flyingMonster(name) {
return {
...flyer({name}),
...attacker({name}),
}
}
function swimmingMonster(name) {
return {
...swimmer({name}),
...attacker({name}),
}
}
const daynasor = monster('daynasor');
daynasor.walk();
daynasor.attack();
const qrsh = swimmingMonster('qrsh');
qrsh.swim();
qrsh.attack();
const saqar = flyingMonster('saqar');
saqar.fly();
saqar.attack();
class Monster {
constructor(name) {
this.name = name;
}
attack() {
console.log(this.name + ' can attack');
}
walk() {
console.log(this.name + ' can walk');
}
}
class FlyingMonster extends Monster {
fly() {
console.log(this.name + ' can fly');
}
}
class SwimmingMonster extends Monster {
swim() {
console.log(this.name + ' can swim');
}
}
const daynasor = new Monster('daynasor');
const qrsh = new SwimmingMonster('qrsh');
const saqar = new FlyingMonster('saqar');
daynasor.attack();
daynasor.walk();
qrsh.walk(); // this is not right
qrsh.attack();
qrsh.swim();
saqar.walk();
saqar.attack();
saqar.fly();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment