-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #8 from shubhamgautam89/pattern/observer
mixin pattern
- Loading branch information
Showing
3 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
/* | ||
A mixin is an object that we can use in order to add reusable functionality to another object or class, without using inheritance. We can't use mixins on their own: their sole purpose is to add functionality to objects or classes without inheritance. | ||
*/ | ||
|
||
//simple example with prototype | ||
|
||
export class Dog { | ||
constructor(name) { | ||
this.name = name; | ||
} | ||
} | ||
|
||
export class Bird { | ||
constructor(name) { | ||
this.name = name; | ||
} | ||
} | ||
|
||
export class Fish { | ||
constructor(name) { | ||
this.name = name; | ||
} | ||
} | ||
|
||
const dogFunctionality = { | ||
bark: () => "Woof!", | ||
wagTail: () => "Wagging my tail", | ||
play: () => "Playing!", | ||
}; | ||
|
||
const flyMixin = { | ||
fly() { | ||
return "fly"; | ||
}, | ||
}; | ||
|
||
const swimMixin = { | ||
swim() { | ||
return "swim"; | ||
}, | ||
}; | ||
|
||
Object.assign(Dog.prototype, dogFunctionality); | ||
Object.assign(Bird.prototype, flyMixin); | ||
Object.assign(Fish.prototype, swimMixin); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { Bird, Dog, Fish } from "./mixin"; | ||
|
||
const tommyDog = new Dog("tommy"); | ||
const nemoFish = new Fish("nemo"); | ||
const redBird = new Bird("red"); | ||
|
||
test("dog test cases", () => { | ||
expect(tommyDog.name).toBe("tommy"); | ||
expect(tommyDog.bark()).toBe("Woof!"); | ||
expect(tommyDog.wagTail()).toBe("Wagging my tail"); | ||
}); | ||
|
||
test("fish test cases", () => { | ||
expect(nemoFish.name).toBe("nemo"); | ||
expect(nemoFish.swim()).toBe("swim"); | ||
expect(nemoFish).not.toHaveProperty("fly"); | ||
}); | ||
|
||
test("bird test cases", () => { | ||
expect(redBird.name).toBe("red"); | ||
expect(redBird.fly()).toBe("fly"); | ||
expect(redBird).not.toHaveProperty("swim"); | ||
}); |
File renamed without changes.