Skip to content

Commit

Permalink
Merge pull request #8 from shubhamgautam89/pattern/observer
Browse files Browse the repository at this point in the history
mixin pattern
  • Loading branch information
shubhamgautam89 authored Oct 17, 2023
2 parents 52f6a5e + 61cd05e commit 18dc71b
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
45 changes: 45 additions & 0 deletions patterns/mixin/mixin.js
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);
23 changes: 23 additions & 0 deletions patterns/mixin/mixin.test.js
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.

0 comments on commit 18dc71b

Please sign in to comment.