Created
March 13, 2021 14:27
-
-
Save danBamikiya/4d411d9233a2d9e993f1872fd8c46e3a to your computer and use it in GitHub Desktop.
File containing some topics I studied when learning JavaScript
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
/* Learning about arrays of objects */ | |
const contacts = [ | |
{ | |
firstName: "Kristian", | |
lastName: "Vos", | |
number: "unknown", | |
likes: ["JavaScript", "Gaming", "Foxes"] | |
}, | |
{ | |
firstName: "Sherlock", | |
lastName: "Holmes", | |
number: "11111189", | |
likes: ["Intriguing Cases", "Violin"] | |
}, | |
{ | |
firstName: "Heroku", | |
lastName: "Varshan", | |
number: "1234567890", | |
likes: ["Boxing", "Cycling", "WeightLifting"] | |
} | |
]; | |
const evaluation = (name, prop) => { | |
for (var i = 0; i < contacts.length; i++) { | |
if (contacts[i].firstName === name) { | |
return contacts[i][prop] || "No such property"; | |
} | |
} | |
return "No such contact"; | |
}; | |
console.log(evaluation("Sherlock", "likes")); // to test function | |
// Learning the for...of loop | |
for (const val of contacts) { | |
console.log(val.lastName); | |
} | |
// Learning Immediately Invoked Function Expressions (IIFE) | |
const value = (function randomWhlNum() { | |
return Math.floor(Math.random() * 5); | |
})(); | |
console.log(value); | |
// This function loops through an array comparing each value with the highest value found | |
const numbers = [20, 10, 67, 23, 900, 97, -Infinity]; // the -Infinity is included to make sure that the function can also loop through the array even if -Infinity is included | |
let maximum = -Infinity; | |
let reduced = numbers.length; | |
const myMaxNumber = (numbers => { | |
for (reduced--; numbers[reduced] >= maximum; reduced--) { | |
maximum = numbers[reduced]; | |
} | |
return `The highest number in the array 'numbers' is: ${maximum}`; | |
})(numbers); | |
console.log(myMaxNumber); // OR We can use a while loop | |
{ | |
while (reduced--) { | |
if (numbers[reduced] >= maximum) { | |
maximum = numbers[reduced]; | |
} | |
} | |
console.log(`See? Its the same value even though we used a while loop: ${maximum}\n`); | |
} /* OR we can use the apply() method */ | |
{ | |
const maximus = Math.max.apply(null, numbers); | |
console.log(maximus); /* OR using the spread operator */ | |
const maximus_1 = Math.max(...numbers); | |
console.log(maximus_1); | |
} | |
//***********Array methods + Higher Order Array methods************// | |
// This outputs out every array item using the 'forEach()' array iteration method | |
console.time( | |
"test forEach() array iteration method" | |
); /** This starts a timer for the forEach() method*/ | |
function anotherFunction() { | |
let txt = ""; | |
const number = [45, 4, 9, 16, 25]; | |
number.forEach(value => { | |
txt += `This is one of the array items ${value}\n`; | |
}); | |
return ( | |
"This outputs every array item using the 'forEach()' array iteration method\n" + txt | |
); | |
} | |
console.log(anotherFunction()); | |
console.timeEnd( | |
"test forEach() array iteration method" | |
); /** This ends the timer for the forEach() method*/ | |
//This outputs out every array item using the 'map()' array iteration method | |
console.time( | |
"test map() array iteration method" | |
); /** This starts the timer for the map() method*/ | |
function anotherFunctionAgain() { | |
let txt = ""; | |
const number = [45, 4, 9, 16, 25]; | |
number.map(value => { | |
txt += `This is one of the array items ${value}\n`; | |
}); | |
return "This outputs every array item using the 'map()' array iteration method\n" + txt; | |
} | |
console.log(anotherFunctionAgain()); | |
console.timeEnd( | |
"test map() array iteration method" | |
); /** This ends the timer for the map() method*/ | |
//This function outputs every array item that is greater than the number '18' using the 'filter()' array iteration method | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
const Over18 = ages.filter(value => value > 18); | |
const Over18_output = `These are the age over 18: ${Over18}`; | |
console.log(Over18_output); | |
} | |
{ | |
// This is to filter the numbers from any variable no of arrays and sum them up together !Not yet done! | |
let yetAnotherSum = (...num) => { | |
let no = num.filter(value => { | |
value === isFinite(); | |
}); | |
return no; | |
}; | |
console.log(yetAnotherSum(1, "yet", 7)); | |
} | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
var arrayChecker = Array.isArray(ages); | |
console.log( | |
`This checks if 'ages' is an array using "Array.isArray()" method -- yes its an array cuz it outputs ${arrayChecker}` | |
); | |
} | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
var arrayChecker = ages instanceof Array; | |
console.log( | |
`This checks if 'ages' is also an array using the "instanceof Array" operator -- yes its also an array cuz it outputs ${arrayChecker}` | |
); | |
} | |
// Lets sort the array 'ages' numerically in ascending order | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
const sorter = ages.sort((a, b) => a - b); | |
const sorter_output = `${sorter} //This array is sorted numerically in an ascending order`; | |
console.log(sorter_output); | |
} | |
// Lets sort the array 'ages' numerically in a random order | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
const sorter = ages.sort((a, b) => 0.5 - Math.random()); | |
const sorter_output = `${sorter} //This array is sorted numerically in a random order`; | |
console.log(sorter_output); | |
} | |
// Lets add up the array 'ages' using the reduce() method | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
const sum = ages.reduce((total, value) => total + value); | |
const sum_output = `${sum} //This is the total sum of the values of the array 'ages' using the array method of reduce()`; | |
console.log(sum_output); | |
} | |
// Lets add up the array 'ages' with an initial value of 100 using the reduceRight() method | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
const sum = ages.reduceRight((total, value) => total + value, 100); | |
const sum_output = `${sum} //This is the total sum of the array 'ages' using the array method 'reduceRight()' with an initial value of 100`; | |
console.log(sum_output); | |
} | |
// Lets check if every value in the array 'ages' is larger than 18 using the every() method | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
const largerThan_18 = ages.every(value => value > 18); | |
const largerThan_18_output = `${largerThan_18} //This means that checking if the values are larger than 18 in the array 'ages' (using the every() method) will return ${largerThan_18} `; | |
console.log(largerThan_18_output); | |
} | |
// Lets check if some values in the array 'ages' are larger than 18 using the some() method | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
const largerThan_18 = ages.some(value => value > 18); | |
const largerThan_18_output = `${largerThan_18} //This means that checking if some of the values are larger than 18 in the array 'ages' (using the every() method) will return ${largerThan_18} `; | |
console.log(largerThan_18_output); | |
} | |
// Lets check the first position of 'apple' in the array below | |
{ | |
const fruits = ["apple", "banana", "pawpaw", "mangoes", "apple"]; | |
const fruitsIndex = fruits.indexOf("apple"); | |
const fruitsIndex_output = `The index of 'apple' in the array is: ${fruitsIndex}, which is position: ${ | |
fruitsIndex + 1 | |
}`; | |
console.log(fruitsIndex_output); | |
} | |
// Lets check for the first element in the array 'ages' that is larger than 18 and also its index | |
{ | |
const ages = [45, 4, 9, 16, 25]; | |
const firstElementLargerThan18_value = ages.find(value => value > 18); | |
const firstElementLargerThan18_index = ages.findIndex(value => value > 18); | |
const firstElementLargerThan18_output = `The first element larger than 18 in the array 'ages' is: ${firstElementLargerThan18_value} and its index is: ${firstElementLargerThan18_index}`; | |
console.log(firstElementLargerThan18_output); | |
} | |
//*************End of Array methods + Higher Order Array methods************// | |
// playing with object properties | |
var person = { | |
firstName: "John", | |
lastName: "Doe", | |
id: 5566 | |
}; | |
person.fullName = function () { | |
return this.firstName + " " + this.lastName; | |
}; | |
console.log("My Father is " + person.fullName()); | |
//**********************OOP***********************// | |
{ | |
//Constructor function | |
function UserData(first, last, age, eye, nationality) { | |
this.firstName = first; | |
this.lastName = last; | |
this.age = age; | |
this.eyeColor = eye; | |
this.Nationality = nationality; | |
} | |
// Instantiate object | |
let User1 = new UserData("Akshay", "Tamil", 16, "blue", "American"); | |
console.log(User1); | |
//Add a method to the constructor function | |
UserData.prototype.changeNationality = function (new_nationality) { | |
this.Nationality = new_nationality; | |
}; | |
// Instantiate the object method | |
User1.changeNationality("Swedish"); | |
console.log(`${User1.firstName} you changed your nationality to ${User1.Nationality}`); | |
UserData.prototype.getProps = function () { | |
return [this.firstName, this.lastName, this.age, this.eyeColor, this.Nationality]; | |
}; | |
console.log(User1.getProps()); | |
/** Adding or changing an object property */ | |
// Syntax : Object.defineProperty(object, property, {value : value}); | |
// Define Object | |
var obj = { counter: 0 }; | |
// Add the property | |
Object.defineProperty(obj, "increment", { | |
get: function () { | |
return this.counter++; | |
} | |
}); | |
// Call the property | |
obj.increment; // so that the console can output the right value/process it | |
console.log(obj.increment); | |
/** Adding or changing many object properties */ | |
Object.defineProperties(object, descriptors); | |
/** Accessing Properties */ | |
Object.getOwnPropertyDescriptor(object, property); | |
/** Returns all properties as an array */ | |
Object.getOwnPropertyNames(object); | |
/** Returns enumerable properties as an array */ | |
Object.keys(object); | |
/** Accessing the prototype */ | |
Object.getPrototypeOf(object); | |
/** Prevents adding properties to an object */ | |
Object.preventExtensions(object); | |
/** Returns true if properties can be added to an object */ | |
Object.isExtensible(object); | |
/** Prevents changes of object properties (not values) */ | |
Object.seal(object); | |
/** Returns true if object is sealed */ | |
Object.isSealed(object); | |
/** Prevents any changes to an object */ | |
Object.freeze(object); | |
/** Returns true if object is frozen*/ | |
Object.isFrozen(object); | |
} | |
{ | |
// Lets get into Classes | |
class Thermostat { | |
constructor(temp) { | |
this._temp = (5 / 9) * (temp - 32); | |
} | |
get temperature() { | |
return this._temp; | |
} | |
set temperature(updatedTemp) { | |
this._temp = (5 / 9) * (updatedTemp - 32); | |
} | |
} | |
const User1 = new Thermostat(77); | |
let User_value = `${User1.temperature}°C`; | |
console.log(User_value); | |
User1.temperature = 56; | |
User_value = `${User1.temperature}°C`; | |
console.log(User_value); | |
} | |
//Lets get into Dates | |
Date.prototype.myDate = function () { | |
if (this.getDay() == 0) { | |
this.myProp = "Sunday"; | |
} else if (this.getDay() == 1) { | |
this.myProp = "Monday"; | |
} else if (this.getDay() == 2) { | |
this.myProp = "Tuesday"; | |
} else if (this.getDay() == 3) { | |
this.myProp = "Wednesday"; | |
} else if (this.getDay() == 4) { | |
this.myProp = "Thursday"; | |
} else if (this.getDay() == 6) { | |
this.myProp = "Saturday"; | |
} else { | |
return "your code isn't working"; | |
} | |
}; | |
function myFunction() { | |
var d = new Date(); | |
d.myDate(); | |
console.log(d.Prop); | |
} | |
//**********************WEB Storage***********************// | |
/** The localStorage and sessionStorage properties allow to save key/value pairs in a web browser. */ | |
/** Local Storage */ | |
// The localStorage object stores data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year. | |
{ | |
// Check browser support | |
if (typeof Storage !== undefined) { | |
// Store | |
localStorage.setItem("testname", "JavaScript_Playground"); | |
// Retrieve | |
document.write(localStorage.getItem("testname")); | |
} else { | |
document.write("Your browser does'nt support WEB Storage..."); | |
} | |
// Get the name of the first local storage item: | |
console.log(localStorage.key(0)); | |
// Removing data from localStorage | |
localStorage.removeItem("testname"); | |
// Clearing all saved data in localStorage for the particular domain you're in | |
localStorage.clear(); | |
} | |
// this will check if an item "checkcount" is stored in the localStorage nd if it is it coverts the item value (which is stored as a string) to a Number then adds 1, if it isn't it stores it with a value of 1; | |
{ | |
if (typeof Storage !== undefined) { | |
if (localStorage.checkcount) { | |
localStorage.checkcount = Number(localStorage.checkcount) + 1; // converts the value of checkcount which is numeric string to a number | |
} else { | |
localStorage.checkcount = 1; | |
} | |
document.write = `You have stored one item with a value of ${localStorage.checkcount} in your browser`; | |
} else { | |
document.write = "Sorry your browser does'nt support WEB Storage"; | |
} | |
} | |
/** sessionStorage */ | |
// The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed). | |
{ | |
// check browser support | |
if (typeof Storage !== undefined) { | |
// Store | |
sessionStorage.setItem("testname", "JavaScript_Playground"); | |
// Retrieve | |
document.write(sessionStorage.getItem("testname")); | |
} else { | |
document.write("Your browser does'nt support WEB Storage..."); | |
} | |
// Removing data from sessionStorage | |
sessionStorage.removeItem("testname"); | |
} | |
// //**********************Lets get into cookies***********************// | |
function setCookie(cname, cvalue, exdays) { | |
const date = new Date(); | |
date.setTime(date.getTime() + exdays * 24 * 60 * 60 * 1000); | |
const expires = `expires=${date.toUTCString()}`; | |
document.cookie = `${cname}=${cvalue};${expires};path=/`; | |
} | |
function getCookie(cname) { | |
const name = `${cname}=`; | |
const decodedCookie = decodeURIComponent(document.cookie); | |
const ca = decodedCookie.split(";"); | |
let returnedValue; | |
ca.forEach((items) => { | |
while (items.charAt(0) == " ") { | |
items = items.substring(1); | |
} | |
if (items.indexOf(name) == 0) { | |
returnedValue = items.substring(name.length, items.length); | |
} | |
}); | |
return typeof returnedValue === typeof String.name ? returnedValue : ""; | |
} | |
function checkCookie() { | |
let user = getCookie("username"); | |
if (user != "") { | |
alert(`Welcome again ${user}`); | |
} else { | |
user = prompt("Please enter your name:", ""); | |
if (user != "" && user != null) { | |
setCookie("username", user, 30); | |
} | |
} | |
} | |
// to reset the cookies for that domain | |
function Reset() { | |
document.cookie = `username=; expires=${new Date(0).toUTCString()}; path=/;`; | |
} | |
// Lets get into Math Object | |
{ | |
const PI = Math.PI; | |
const round = Math.round(4.4); // returns the value of the argument to its nearest integer | |
const pow = Math.pow(2, 9); // returns the value of the first argument to the power of the second argument | |
const sqrt = Math.sqrt(96); | |
console.log(`${PI},\n ${round},\n ${pow},\n ${sqrt}\n`); | |
console.log(Math.sqrt(Math.round(Math.pow(Math.PI, 2)))); | |
const abs_ceil = Math.ceil(Math.abs(-3.16)); // Math.abs returns the absolute (positive) value of its argument and Math.ceil returns the value of arguments rounded up to its nearest integer | |
const abs_floor = Math.floor(Math.abs(-3.16)); // Math.floor returns the value of arguments rounded down to its nearest integer | |
const sine = Math.sin((180 * Math.PI) / 180); | |
const cosine = Math.cos((180 * Math.PI) / 180); | |
const min = Math.min(0, 150, 30, 20, -8, -200); | |
const max = Math.max(0, 150, 30, 20, -8, -200); | |
const random = Math.random(); // returns a random number between 0 (inclusive), and 1 (exclusive) | |
const randomInt = Math.floor(Math.random() * 10); // returns a random integer from 0 to 9 | |
const randdomInt_1 = Math.floor(Math.random() * 11); // returns a random integer from 0 to 10 | |
const getRndInteger = ((min, max) => { | |
return Math.floor(Math.random() * (max - min)) + min; | |
})(0, 10); // returns a random number between min (included) and max (excluded) | |
const getRndInteger_1 = ((min, max) => { | |
return Math.floor(Math.random() * max - min + 1) + min; | |
})(1, 10); | |
console.log(` | |
${abs_ceil},\n | |
${abs_floor},\n | |
${sine},\n | |
${cosine},\n | |
${min},\n | |
${max},\n | |
${random},\n | |
${randomInt},\n | |
${randdomInt_1},\n | |
${getRndInteger},\n | |
${getRndInteger_1}\n | |
`); | |
} | |
/** Lets get into JSON */ | |
{ | |
let obj = | |
'{ "Owner" : "Varshan", "age" : 50, "birth" : "2020-08-20T12:00:00Z", "pets" : [ { "animal" : "dog", "name": "Ganga" }, { "animal" : "jaguar", "name" : "Jolie" }, { "animal" : "cow", "name" : "drizzy" } ] }'; | |
let dateGetter = JSON.parse(obj, (key, value) => { | |
if (key === "birth") { | |
return new Date(value).toDateString(); | |
} else { | |
return value; | |
} | |
}); | |
console.log( | |
`Owner : ${dateGetter.Owner}, age : ${dateGetter.age}, DOB : ${dateGetter.birth}, firstpet : ${dateGetter.pets[0].name} - a ${dateGetter.pets[0].animal}` | |
); | |
let arr = [ | |
"accountant", | |
"business manager", | |
"product manager", | |
"project manager", | |
"cheif technical officer" | |
]; | |
let myJSON = JSON.stringify(arr); | |
console.log(`${myJSON} : a ${typeof myJSON}`); | |
let myObj = '{ "name": "John", "age": 30, "car": null }'; | |
let myObj_parsed = JSON.parse(myObj); | |
let element = ""; | |
for (const key in myObj_parsed) { | |
if (myObj_parsed.hasOwnProperty(key)) { | |
element += `${key} : ${myObj_parsed[key]} `; | |
} | |
} | |
console.log(element); | |
let anotherObj, | |
index, | |
j, | |
model, | |
elem = ""; | |
anotherObj = `{ "name" : "John", "age" : 30, "cars" : [ { "name" : "Ford", "models" : [ "Fiesta", "Focus", "Mustang" ] }, { "name" : "BMW", "models" : [ "320", "X3", "X5" ] }, { "name" : "Fiat", "models" : [ "500", "Panda" ] } ] }`; | |
// anotherObj = { | |
// name: "John", | |
// age: 30, | |
// cars: [ | |
// { name: "Ford", models: ["Fiesta", "Focus", "Mustang"] }, | |
// { name: "BMW", models: ["320", "X3", "X5"] }, | |
// { name: "Fiat", models: ["500", "Panda"] } | |
// ] | |
// }; | |
// let anotherObj_stringified = JSON.stringify(anotherObj); | |
let anotherObj_parsed = JSON.parse(anotherObj); | |
if (anotherObj_parsed.hasOwnProperty("cars")) { | |
for (index in anotherObj_parsed.cars) { | |
elem += `"<h2>" ${anotherObj_parsed.cars[index].name} "</h2>"\n`; | |
for (j in anotherObj_parsed.cars[index].models) { | |
elem += `${anotherObj_parsed.cars[index].models[j]}\n`; | |
} | |
} | |
} | |
console.log(elem); | |
} | |
/** Closures */ | |
let subtract = (() => { | |
let tract = 0; | |
return () => { | |
tract--; | |
return tract; | |
}; | |
})(); | |
function anotherFunction() { | |
console.log(subtract()); | |
} | |
/*===== More about OOP ======*/ | |
/** Inheritance */ | |
function Book(title, author, year) { | |
this.title = title; | |
this.author = author; | |
this.year = year; | |
} | |
//getSummary | |
Book.prototype.getSummary = function () { | |
return `${this.title} was written by ${this.author} in ${this.year}`; | |
}; // prototypes are used to add methods to a constructor function or classes also to add methods to classes or constructor functions if we don't want those methods in every instances of the class or constructor function created | |
// Magazine Constructor | |
function Magazine(title, author, year, month) { | |
Book.call(this, title, author, year); | |
this.month = month; | |
} | |
// Inherit Prototype | |
Magazine.prototype = Object.create(Book.prototype); | |
// Instantiate Magazine Object | |
const mag1 = new Magazine("Mag One", "Sherlock Holmes", "2020", "Mar"); | |
console.log(mag1.getSummary()); | |
// Use Magazine Constructor | |
Magazine.prototype.constructor = Magazine; | |
console.log(mag1); | |
/** Creating Objects */ | |
// Object Of Protos | |
const bookProtos = { | |
getSummary: function () { | |
return `${this.title} was written by ${this.author} in ${this.year}`; | |
}, | |
getAge: function () { | |
const years = new Date().getFullYear() - this.year; | |
return `${this.title} is ${years} years old`; | |
} | |
}; | |
// Create Object | |
const book1 = Object.create(bookProtos); | |
book1.title = "Book One"; | |
book1.author = "John Doe"; | |
book1.year = "2013"; | |
console.log(book1); | |
const book3 = Object.create(bookProtos, { | |
title: { value: "Tiktology" }, | |
author: { value: "Mrs Cigar" }, | |
year: { value: "2020" } | |
}); | |
console.log(book3); | |
/** Subclasses */ | |
{ | |
class Book { | |
constructor(title, author, year) { | |
this.title = title; | |
this.author = author; | |
this.year = year; | |
} | |
getSummary() { | |
return `${this.title} was written by ${this.author} in ${this.year}`; | |
} | |
} | |
// Magazine Subclasses | |
class Magazine extends Book { | |
constructor(title, author, year, month) { | |
super(title, author, year); | |
this.month = month; | |
} | |
} | |
// Instantiate Magazine | |
const mag1 = new Magazine("The Flash", "Greg Berlanti", "2014", "Jan"); | |
console.log(mag1); | |
console.log(mag1.getSummary()); | |
} | |
{ | |
/** Calling static methods from other static methods */ | |
class StaticMethodCall { | |
static staticMethod() { | |
return "Static method has been called"; | |
} | |
static anotherStaticMethod() { | |
return this.staticMethod() + " from another static method"; | |
} | |
} | |
console.log(StaticMethodCall.anotherStaticMethod()); | |
// 'Static method has been called from another static method' | |
} | |
{ | |
/** Calling static method from class constructor and other methods */ | |
class StaticMethodCall { | |
constructor() { | |
console.log(StaticMethodCall.staticMethod()); | |
// 'static method has been called.' | |
console.log(this.constructor.staticMethod()); | |
// 'static method has been called.' | |
} | |
static staticMethod() { | |
return "static method has been called."; | |
} | |
} | |
const MethodCall = new StaticMethodCall(); | |
console.log(MethodCall); | |
} | |
{ | |
class Triple { | |
static triple(n) { | |
if (n === undefined) { | |
n = 1; | |
} | |
return n * 3; | |
} | |
} | |
class BiggerTriple extends Triple { | |
static triple(n) { | |
return super.triple(n) * super.triple(n); | |
} | |
} | |
console.log(Triple.triple()); // 3 | |
console.log(Triple.triple(6)); // 18 | |
var tp = new Triple(); | |
console.log(BiggerTriple.triple(3)); | |
// 81 (not affected by parent's instantiation) | |
/** console.log(tp.triple()); */ | |
// 'tp.triple is not a function'. | |
} | |
{ | |
/** more static methods */ | |
class Point { | |
constructor(x, y) { | |
this.x = x; | |
this.y = y; | |
} | |
static distance(a, b) { | |
const dx = a.x - b.x; | |
const dy = a.y - b.y; | |
return Math.hypot(dx, dy); | |
} | |
} | |
const p1 = new Point(5, 5); | |
const p2 = new Point(10, 10); | |
console.log(Point.distance(p1, p2)); // 7.0710678118654755 | |
} | |
{ | |
/** Using extends with built-in objects */ | |
class myDate extends Date { | |
constructor() { | |
super(); | |
} | |
getFormattedDate() { | |
const months = [ | |
"Jan", | |
"Feb", | |
"Mar", | |
"Apr", | |
"May", | |
"Jun", | |
"Jul", | |
"Aug", | |
"Sep", | |
"Oct", | |
"Nov", | |
"Dec" | |
]; | |
return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear(); | |
} | |
} | |
} | |
class Rect { | |
constructor(width, height) { | |
this.width = width; | |
this.height = height; | |
} | |
} | |
class Square extends Rect { | |
constructor(width, height, area, perimeter) { | |
super(width, height); | |
this.area = area; | |
this.perimeter = perimeter; | |
} | |
get all() { | |
return `${this.area}, ${this.height}, ${this.width}, ${this.perimeter}`; | |
} | |
} | |
const favShape = new Square(10, 17, 54, 90); | |
console.log(favShape.all); | |
/*===== Design Patterns ======*/ | |
// Constructor Pattern | |
// we define a constructor for Person objects | |
function Person(name, age, isDeveloper) { | |
this.name = name; | |
this.age = age; | |
this.isDeveloper = isDeveloper || false; | |
} | |
// we extend the function's prototype | |
Person.prototype.writesCode = function () { | |
console.log( | |
this.isDeveloper ? "This person does write code" : "This person does not write code" | |
); | |
}; | |
// creates a Person instance with properties name: Bob, age: 38, isDeveloper: true and a method writesCode | |
const person1 = new Person("Bob", 38, true); | |
// creates a Person instance with properties name: Alice, age: 32, isDeveloper: false and a method writesCode | |
const person2 = new Person("Alice", 32); | |
// prints out: This person does write code | |
person1.writesCode(); | |
// prints out: this person does not write code | |
person2.writesCode(); | |
// Now, both instances of the Person constructor can access a shared instance of the writesCode() method. | |
// Module Pattern | |
// through the use of a closure we expose an object | |
// as a public API which manages the private objects array | |
const collection = (() => { | |
// private members | |
const objects = []; | |
// public members | |
return { | |
addObject: object => { | |
objects.push(object); | |
}, | |
removeObject: object => { | |
const index = objects.indexOf(object); | |
if (index >= 0) { | |
objects.splice(index, 1); | |
} | |
}, | |
getObjects: () => JSON.parse(JSON.stringify(objects)) | |
}; | |
})(); | |
collection.addObject("Bob"); | |
collection.addObject("Alice"); | |
collection.addObject("Franck"); | |
console.log(collection.getObjects()); | |
collection.removeObject("Alice"); | |
console.log(collection.getObjects()); | |
// Revealing Module Pattern | |
// we write the entire object logic as private members and | |
// expose an anonymous object which maps members we wish to reveal | |
// to their corresponding public members | |
const namesCollection = (() => { | |
// private members | |
const objects = []; | |
const addObject = object => objects.push(object); | |
const removeObject = object => { | |
const index = objects.indexOf(object); | |
if (index >= 0) { | |
objects.splice(index, 1); | |
} | |
}; | |
const getObjects = () => JSON.parse(JSON.stringify(objects)); | |
// public members | |
return { | |
addName: addObject, | |
removeName: removeObject, | |
getNames: getObjects | |
}; | |
})(); | |
namesCollection.addName("Bob"); | |
namesCollection.addName("Alice"); | |
namesCollection.addName("Franck"); | |
// prints ["Bob", "Alice", "Franck"] | |
console.log(namesCollection.getNames()); | |
namesCollection.removeName("Alice"); | |
// prints ["Bob", "Franck"] | |
console.log(namesCollection.getNames()); | |
// Singleton Pattern | |
const singleton = (() => { | |
// private singleton value which gets initialized only once | |
let config; | |
function initializeConfiguration(values = {}) { | |
this.randomNumber = Math.random(); | |
this.number = values.number || 5; | |
this.size = values.size || 10; | |
} | |
// we export the centralized method for retrieving the singleton value | |
return { | |
getConfig: values => { | |
// we initailize the singleton value only once | |
if (config === undefined) { | |
config = new initializeConfiguration(values); | |
} | |
// and return the same config value wherever it is asked for | |
return config; | |
} | |
}; | |
})(); | |
const configObject = singleton.getConfig({ size: 8 }); | |
// prints number: 5, size: 8, randomNumber: someRandomDecimalValue | |
console.log(configObject); | |
var configObject1 = singleton.getConfig({ number: 8 }); | |
// prints number: 5, size: 8, randomNumber: same randomDecimalValue as in first config | |
console.log(configObject1); | |
// Observer Pattern | |
const publisherSubscriber = {}; | |
// we send in a container object which will handle the subscriptions and publishings | |
(container => { | |
// the id represents a unique subscription id to a topic | |
let id = 0; | |
// we subscribe to a specific topic by sending in a callback function to be executed on event firing | |
container.subscribe = (topic, f) => { | |
if (!(topic in container)) { | |
container[topic] = []; | |
} | |
container[topic].push({ | |
id: ++id, | |
callback: f | |
}); | |
return id; | |
}; | |
// each subscription has its own unique ID, which we use to remove a subscriber from a certain topic | |
container.unsubscribe = (topic, id) => { | |
const subscribers = []; | |
container[topic].forEach(subscriber => { | |
if (subscriber.id !== id) { | |
subscribers.push(subscriber); | |
} | |
}); | |
container[topic] = subscribers; | |
}; | |
container.publish = (topic, data) => { | |
container[topic].forEach(subscriber => subscriber.callback(data)); | |
}; | |
})(publisherSubscriber); | |
var subscriptionID2 = publisherSubscriber.subscribe("mouseHovered", function (data) { | |
console.log( | |
"I am Bob's callback function for a hovered mouse event and this is my event data: " + | |
JSON.stringify(data) | |
); | |
}); | |
var subscriptionID3 = publisherSubscriber.subscribe("mouseClicked", function (data) { | |
console.log( | |
"I am Alice's callback function for a mouse clicked event and this is my event data: " + | |
JSON.stringify(data) | |
); | |
}); | |
// NOTE: after publishing an event with its data, all of the | |
// subscribed callbacks will execute and will receive | |
// a data object from the object firing the event | |
// there are 3 console.logs executed | |
publisherSubscriber.publish("mouseClicked", { data: "data1" }); | |
publisherSubscriber.publish("mouseHovered", { data: "data2" }); | |
// we unsubscribe from an event by removing the subscription ID | |
publisherSubscriber.unsubscribe("mouseClicked", subscriptionID3); | |
// there are 2 console.logs executed | |
publisherSubscriber.publish("mouseClicked", { data: "data1" }); | |
publisherSubscriber.publish("mouseHovered", { data: "data2" }); | |
// Prototype Pattern | |
class actorPrototype { | |
sayHi() { | |
console.log("Hello, my name is " + this.name + ", and I am " + this.age); | |
} | |
sayBye() { | |
console.log("Bye Bye"); | |
} | |
} | |
class Actor extends actorPrototype { | |
constructor(name = "John Doe", age = 26) { | |
super(); | |
this.name = name; | |
this.age = age; | |
} | |
} | |
const actor1 = new Actor(); | |
const actor2 = new Actor("Bob", 38); | |
// prints out Hello, my name is John Doe, and I am 26 | |
actor1.sayHi(); | |
// prints out Hello, my name is Bob, and I am 38 | |
actor2.sayHi(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment