Skip to content

Commit 237f2dd

Browse files
authored
code
1 parent 134072b commit 237f2dd

14 files changed

Lines changed: 563 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// ==> craete object by
2+
3+
let instance1 = {};
4+
// or
5+
let instance2 = Object.create(Object.prototype);
6+
// or
7+
let instance3 = new Object();
8+
9+
10+
// ==> add properties:
11+
12+
// The . notation
13+
instance.key = 'value';
14+
15+
// brackets notation
16+
instance['key'] = 'value';
17+
18+
// defining a property with Object.defineProperty
19+
Object.defineProperty(instance, 'key', {
20+
value: 'value',
21+
writable: true,
22+
enumerable: true,
23+
configurable: true
24+
});
25+
26+
// defining multiple properties with Object.defineProperties
27+
Object.defineProperties(instance, {
28+
'firstKey': {
29+
value: 'first key value',
30+
writable: true
31+
},
32+
'secondKey': {
33+
value: 'second key value',
34+
writable: false
35+
}
36+
});
37+
38+
39+
// ==> create a class with constructor and prototype(with shared methods)
40+
41+
// We define a constructor for Person
42+
function Person(name, age, isDeveloper) {
43+
this.name = name;
44+
this.age = age;
45+
this.isDeveloper = isDeveloper || false;
46+
}
47+
48+
// Then we extend the prototype, this way we make JavaScript
49+
// point to this function when we call it on a Person
50+
Person.prototype.writesCode = function () {
51+
console.log(this.isDeveloper ? 'this person writes code' : 'this person does not writes code')
52+
}
53+
54+
55+
// Create a person with: name = Ana, age = 32,
56+
// isDeveloper = true and a method writesCode
57+
let person1 = new Person('Ana', 32, true);
58+
59+
// Create a person with: name = Bob, age = 36,
60+
// isDeveloper = false and a method writesCode
61+
let person2 = new Person('Bob', 36);
62+
63+
// prints this person writes code
64+
person1.writesCode();
65+
// prints this person does not writes code
66+
person2.writesCode();
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Using a closure we will expose an object
2+
// as part of a public API that manages its
3+
// private parts
4+
let fruitsCollection = (() => {
5+
// private
6+
let objects = [];
7+
8+
// public
9+
return {
10+
addObject: (object) => {
11+
objects.push(object);
12+
},
13+
removeObject: (object) => {
14+
let index = objects.indexOf(object);
15+
if (index >= 0) {
16+
objects.splice(index, 1);
17+
}
18+
},
19+
getObjects: () => JSON.parse(JSON.stringify(objects))
20+
};
21+
})(); // notice the execution
22+
23+
fruitsCollection.addObject("apple");
24+
fruitsCollection.addObject("orange");
25+
fruitsCollection.addObject("banana");
26+
27+
// prints: ["apple", "orange", "banana"]
28+
console.log(fruitsCollection.getObjects());
29+
30+
fruitsCollection.removeObject("apple");
31+
32+
// prints: ["orange", "banana"]
33+
console.log(fruitsCollection.getObjects());
34+
35+
// The greatest utility of this pattern is to make a clear separation between the public and private parts of an object.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// When methods are defined in the constructor itself
2+
// in this case , every object will have its own copy of the method
3+
class TeslaCar {
4+
constructor(model) {
5+
this.model = model;
6+
this.getCarModel = function () { return this.model; };
7+
}
8+
}
9+
let t = new TeslaCar('ssada')
10+
let h = new TeslaCar('sasad');
11+
t.getCarModel === h.getCarModel
12+
// false
13+
14+
15+
// When methods are defined in prototype
16+
function Car(model){
17+
this.model = model;
18+
19+
}
20+
Car.prototype.getCarModel = function(){return this.model};
21+
let c = new Car('tesla')
22+
let d = new Car('ssdsda')
23+
c.getCarModel === d.getCarModel
24+
// true
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// https://www.dofactory.com/javascript/design-patterns/singleton
2+
var Singleton = (function () {
3+
var instance;
4+
5+
function createInstance() {
6+
var object = new Object("I am the instance");
7+
return object;
8+
}
9+
10+
return {
11+
getInstance: function () {
12+
if (!instance) {
13+
instance = createInstance();
14+
}
15+
return instance;
16+
}
17+
};
18+
})();
19+
20+
function run() {
21+
22+
var instance1 = Singleton.getInstance();
23+
var instance2 = Singleton.getInstance();
24+
25+
console.log("Same instance? " + (instance1 === instance2));
26+
}
27+
28+
29+
// Using class
30+
// https://www.freecodecamp.org/news/singleton-design-pattern-with-javascript/#:~:text=Singleton%20is%20a%20design%20pattern,want%20to%20access%20this%20state.
31+
let instance;
32+
let globalState = {
33+
color: ""
34+
};
35+
36+
class StateUtility {
37+
constructor() {
38+
if (instance) {
39+
throw new Error("New instance cannot be created!!");
40+
}
41+
42+
instance = this;
43+
}
44+
45+
getPropertyByName(propertyName) {
46+
return globalState[propertyName];
47+
}
48+
49+
setPropertyValue(propertyName, propertyValue) {
50+
globalState[propertyName] = propertyValue;
51+
}
52+
}
53+
54+
let stateUtilityInstance = Object.freeze(new StateUtility());
55+
56+
export default stateUtilityInstance;
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
const createUser = ({ userName, avatar }) => ({
2+
userName,
3+
avatar,
4+
setUserName(userName) {
5+
this.userName = userName;
6+
return this;
7+
}
8+
});
9+
console.log(createUser({ userName: 'echo', avatar: 'echo.png' }));
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// We have a class or "concrete factory" for each vehicle type
2+
class Car {
3+
constructor () {
4+
this.name = "Car"
5+
this.wheels = 4
6+
}
7+
turnOn = () => console.log("Chacabúm!!")
8+
}
9+
10+
class Truck {
11+
constructor () {
12+
this.name = "Truck"
13+
this.wheels = 8
14+
}
15+
turnOn = () => console.log("RRRRRRRRUUUUUUUUUMMMMMMMMMM!!")
16+
}
17+
18+
class Motorcycle {
19+
constructor () {
20+
this.name = "Motorcycle"
21+
this.wheels = 2
22+
}
23+
turnOn = () => console.log("sssssssssssssssssssssssssssssshhhhhhhhhhham!!")
24+
}
25+
26+
// And and abstract factory that works as a single point of interaction for our clients
27+
// Given the type parameter it receives, it will call the corresponding concrete factory
28+
const vehicleFactory = {
29+
createVehicle: function (type) {
30+
switch (type) {
31+
case "car":
32+
return new Car()
33+
case "truck":
34+
return new Truck()
35+
case "motorcycle":
36+
return new Motorcycle()
37+
default:
38+
return null
39+
}
40+
}
41+
}
42+
43+
const car = vehicleFactory.createVehicle("car") // Car { turnOn: [Function: turnOn], name: 'Car', wheels: 4 }
44+
const truck = vehicleFactory.createVehicle("truck") // Truck { turnOn: [Function: turnOn], name: 'Truck', wheels: 8 }
45+
const motorcycle = vehicleFactory.createVehicle("motorcycle") // Motorcycle { turnOn: [Function: turnOn], name: 'Motorcycle', wheels: 2 }
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// We declare our objects
2+
const bug1 = {
3+
name: "Buggy McFly",
4+
phrase: "Your debugger doesn't work with me!"
5+
}
6+
7+
const bug2 = {
8+
name: "Martiniano Buggland",
9+
phrase: "Can't touch this! Na na na na..."
10+
}
11+
12+
// These functions take an object as parameter and add a method to them
13+
const addFlyingAbility = obj => {
14+
obj.fly = () => console.log(`Now ${obj.name} can fly!`)
15+
}
16+
17+
const addSpeechAbility = obj => {
18+
obj.saySmthg = () => console.log(`${obj.name} walks the walk and talks the talk!`)
19+
}
20+
21+
// Finally we call the builder functions passing the objects as parameters
22+
addFlyingAbility(bug1)
23+
bug1.fly() // output: "Now Buggy McFly can fly!"
24+
25+
addSpeechAbility(bug2)
26+
bug2.saySmthg() // output: "Martiniano Buggland walks the walk and talks the talk!"
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Our array of cities
2+
const citiesHabitantsInMillions = [
3+
{ city: "London", habitants: 8.9 },
4+
{ city: "Rome", habitants: 2.8 },
5+
{ city: "New york", habitants: 8.8 },
6+
{ city: "Paris", habitants: 2.1 },
7+
]
8+
9+
// The new city we want to add
10+
const BuenosAires = {
11+
city: "Buenos Aires",
12+
habitants: 3100000
13+
}
14+
15+
// Our adapter function takes our city and converts the habitants property to the same format all the other cities have
16+
const toMillionsAdapter = city => { city.habitants = parseFloat((city.habitants/1000000).toFixed(1)) }
17+
18+
toMillionsAdapter(BuenosAires)
19+
20+
// We add the new city to the array
21+
citiesHabitantsInMillions.push(BuenosAires)
22+
23+
// And this function returns the largest habitants number
24+
const MostHabitantsInMillions = () => {
25+
return Math.max(...citiesHabitantsInMillions.map(city => city.habitants))
26+
}
27+
28+
console.log(MostHabitantsInMillions()) // 8.9
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// In the observer pattern, the source of data itself (the Subject) knows who all are its observers.
2+
// So, there is no intermediate broker between Subject and Observers. Whereas in pub-sub, the publishers and
3+
// subscribers are loosely coupled, they are unaware of even the existence of each other
4+
class PubSub {
5+
constructor() {
6+
this.observers = {};
7+
}
8+
// add the observer to listener
9+
subscribe = (event, cb) => {
10+
if (this.observers[event]) {
11+
this.observers[event] = [...this.observers[event], cb];
12+
}
13+
else this.observers[event] = [cb];
14+
}
15+
16+
// remove the observer
17+
unsubscribe = (event) => {
18+
let { [event]: a, ...rest } = this.observers;
19+
this.observers = rest;
20+
}
21+
22+
publish = (event, ...data) => {
23+
this.observers[event]?.forEach(listener => {
24+
listener.apply(this, data);
25+
})
26+
}
27+
}
28+
29+
const pubSub = new PubSub();
30+
31+
pubSub.subscribe("event1", (data) => {
32+
console.log("First sub : Event1 data", data);
33+
});
34+
pubSub.subscribe("event1", (data) => {
35+
console.log("Second Sub : Event1 data", data);
36+
});
37+
38+
pubSub.subscribe("event2", (data) => {
39+
console.log("Event2 data", data);
40+
});
41+
pubSub.publish("event1", { name: "IV1" });
42+
pubSub.publish("event2", { name: "IV2" });
43+
pubSub.unsubscribe("event1");
44+
pubSub.publish("event1", { name: "IV23" });
45+
46+
47+
// OUTPUT
48+
49+
// First sub : Event1 data
50+
// {name: "IV1"}
51+
// Second Sub : Event1 data
52+
// {name: "IV1"}
53+
// Event2 data
54+
// {name: "IV2"}
55+
56+
57+
// Observer | PUb SUb
58+
// ---------------- --------
59+
// synchronous | async
60+
// subject knows its observers | subscriber and publisher dont know about each others existance
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<!DOCTYPE html>
2+
<!-- https://www.youtube.com/watch?v=5-gHshKtyAo -->
3+
<html lang="en">
4+
<head>
5+
<meta charset="UTF-8" />
6+
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
7+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
8+
<title>Document</title>
9+
<style>
10+
div {
11+
height: 40px;
12+
width: 300px;
13+
border: 1px solid black;
14+
margin: 5px;
15+
}
16+
</style>
17+
</head>
18+
<body>
19+
Subject : <input type="text" id="subject" />
20+
<br />
21+
Observers:
22+
<div id="observer1"></div>
23+
<div id="observer2"></div>
24+
<div id="observer3"></div>
25+
<script src="script.js"></script>
26+
</body>
27+
</html>

0 commit comments

Comments
 (0)