From 594a4a449ebc9b65fbf64875cacb2c538b7daf41 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:50:11 -0500 Subject: [PATCH 01/31] #00 - JavaScript --- .../javascript/Sac-Corts.js | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Roadmap/00 - SINTAXIS, VARIABLES, TIPOS DE DATOS Y HOLA MUNDO/javascript/Sac-Corts.js diff --git a/Roadmap/00 - SINTAXIS, VARIABLES, TIPOS DE DATOS Y HOLA MUNDO/javascript/Sac-Corts.js b/Roadmap/00 - SINTAXIS, VARIABLES, TIPOS DE DATOS Y HOLA MUNDO/javascript/Sac-Corts.js new file mode 100644 index 0000000000..8604bc91ab --- /dev/null +++ b/Roadmap/00 - SINTAXIS, VARIABLES, TIPOS DE DATOS Y HOLA MUNDO/javascript/Sac-Corts.js @@ -0,0 +1,50 @@ +// JavaScript programming language official website URL: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript + +// Single line comment in JavaScript + +/* +Multi-line comment in JavaScript +It is used to describe longer blocks of code. +or provide detailed information. +*/ + +var myGlobalVariable = "This is a global variable" + +let myLocalVariable = "This is a local variable"; + +const MY_CONSTANT = "This is a constant"; + +// String +let textString = "Hello, I am a string"; +console.log(typeof(textString)) + +// Number +let integer = 42; +console.log(typeof(integer)) + +let float = 3.14; +console.log(typeof(float)) + +// Boolean +let boolean = true; +console.log(typeof(boolean)) + +// Undefined +let undefinedVar; +console.log(typeof(undefinedVar)) + +// Null +let nullVar = null; +console.log(typeof(nullVar)) + +// Symbol +let symbol = Symbol('description'); +console.log(typeof(symbol)) + +// BigInt +let bigInt = BigInt(1234567890123456789012345678901234567890n); +console.log(typeof(bigInt)) + +// Print the required text via terminal +console.log("¡Hello, JavaScript!"); From f4e2b378538b5274f7149d5190dc6af2977f3e9e Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:50:58 -0500 Subject: [PATCH 02/31] #01 - JavaScript --- .../javascript/Sac-Corts.js | 150 ++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 Roadmap/01 - OPERADORES Y ESTRUCTURAS DE CONTROL/javascript/Sac-Corts.js diff --git a/Roadmap/01 - OPERADORES Y ESTRUCTURAS DE CONTROL/javascript/Sac-Corts.js b/Roadmap/01 - OPERADORES Y ESTRUCTURAS DE CONTROL/javascript/Sac-Corts.js new file mode 100644 index 0000000000..9663de3817 --- /dev/null +++ b/Roadmap/01 - OPERADORES Y ESTRUCTURAS DE CONTROL/javascript/Sac-Corts.js @@ -0,0 +1,150 @@ +// Exercise // + +// Arithmetic Operators +let addition = 5 + 3; +console.log("Addition: 5 + 3 = ", addition); + +let subtraction = 10 - 5; +console.log("Subtraction: 10 - 5 = ", subtraction); + +let multiplication = 10 * 5; +console.log("Multiplication: 10 * 5 = ", multiplication); + +let division = 100 / 5; +console.log("Division: 10 / 5 = ", division); + +let _module = 8 % 2; +console.log("Module: 8 % 2 = ", _module); + +let power = 4 ** 2; +console.log("Power: 4 ** 2 = ", power); + +// Assignment Operators +let a = 10; + +a += 2; +console.log("Addition assignment +=: ", a); + +a -= 2; +console.log("Subtraction assignment -=: ", a); + +a *= 4; +console.log("Multiplication assignment *=: ", a); + +a /= 2; +console.log("Division assignment /=: ", a); + +a %= 2; +console.log("Remainder assignment %=: ", a); + +a **= 2; +console.log("Exponentiation assignment **=: ", a); + +// Comparison Operators +console.log("Equality == : ", 5 == "5"); +console.log("Strict equality == : ", 5 === "5"); +console.log("Inequality != : ", 5 != "5"); +console.log("Strict inequality !== : ", 5 !== "5"); +console.log("Greater than > : ", 10 > 5); +console.log("Less than < : ", 10 < 5); +console.log("Greater than or equal >= : ", 5 >= 7); +console.log("Less than or equal <= : ", 5 <= 7); + +// Logical Operators +console.log("Logical AND (&&):", true && false); +console.log("Logical OR (||):", true || false); +console.log("Logical NOT (!):", !false); + +// Identity Operators +let obj1 = { name: "Isaac" }; +let obj2 = { name: "Isaac" }; +let obj3 = obj1; +console.log("Identity (===):", obj1 === obj2); +console.log("Identity (===):", obj1 === obj3); + +// Membership Operators +let array = [1, 2, 3, 4, 5]; +console.log("Membership (in):", 3 in array); +console.log("Membership (includes):", array.includes(3)); + +let obj = { name: "Bob", age: 25 }; +console.log("Membership (in):", "name" in obj); +console.log("Membership (in):", "height" in obj); + +// Bits Operators +console.log("Bitwise AND (&):", 5 & 1); // 101 & 001 = 001 (1) +console.log("Bitwise OR (|):", 5 | 1); // 101 | 001 = 101 (5) +console.log("Bitwise XOR (^):", 5 ^ 1); // 101 ^ 001 = 100 (4) +console.log("Bitwise NOT (~):", ~5); // ~101 = 010 (complemento) +console.log("Bitwise Left Shift (<<):", 5 << 1); // 101 << 1 = 1010 (10) +console.log("Bitwise Right Shift (>>):", 5 >> 1); // 101 >> 1 = 010 (2) +console.log("Bitwise Zero-fill Right Shift (>>>):", 5 >>> 1); // 101 >>> 1 = 010 (2) + +// Control Structures // + +// Conditionals +let num = 10; +if (num > 0) { + console.log("The number is positive"); +} else if (num < 0) { + console.log('The number is negative'); +} else { + console.log('The number is cero'); +} + +switch (num) { + case 1: + console.log('The number is 1'); + break; + case 10: + console.log('The numer is 10') + break; + default: + console.log('The number is not 1 or 10'); +} + +// Iterative +for (let i = 0; i < 5; i++) { + console.log('For loop, i = ', i); +} + +let count = 0; +while (count < 5) { + console.log('While loop, i = ', count); + count++; +} + +let index = 0; +do { + console.log('Do loop, index = ', index); + index++; +} while (index < 5); + +let arrayForOf = ['a', 'b', 'c']; +for (let item of arrayForOf) { + console.log('For-of loop, item = ', item); +} + +let objForIn = { name: 'Alice', age: 25}; +for (let key in objForIn) { + console.log('For-in loop, key = ', key, ', value = ', objForIn[key]); +} + +// Exceptions +try { + let result = 10 / 0; + console.log('Result: ', result); + throw new Error('This is a custom exception'); +} catch (error) { + console.log('An exception was caught: ', error.message); +} finally { + console.log('This block is always executed'); +} + +// Extra Exercise // + +for (let i = 10; i <= 55 ; i++) { + if (i % 2 === 0 && i % 3 !== 0 && i !== 16) { + console.log(i); + } +} \ No newline at end of file From f79705e1dafb0cbc78523a79834960d8fcab49ad Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:51:22 -0500 Subject: [PATCH 03/31] #02 - JavaScript --- .../javascript/Sac-Corts.js | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Roadmap/02 - FUNCIONES Y ALCANCE/javascript/Sac-Corts.js diff --git a/Roadmap/02 - FUNCIONES Y ALCANCE/javascript/Sac-Corts.js b/Roadmap/02 - FUNCIONES Y ALCANCE/javascript/Sac-Corts.js new file mode 100644 index 0000000000..cf0c762fbe --- /dev/null +++ b/Roadmap/02 - FUNCIONES Y ALCANCE/javascript/Sac-Corts.js @@ -0,0 +1,83 @@ +// Exercise // +// Function whitout parameters or return value +function noParameters() { + console.log("This function has no parameters or return value."); +} + +noParameters(); + +// Function with one parameter +function oneParameter(param) { + console.log("The received parameter is: " + param); +} + +oneParameter("Hello World"); + +// Function with multiple parameters +function multipleParameters(param1, param2) { + console.log("The received parameters are: " + param1 + " and " + param2); +} + +multipleParameters('Hello', 'World'); + +// Function with return value +function addition(a, b) { + return console.log(a + b); +} + +addition(4, 10); + +// Nested functions +function outerFunction() { + console.log("This is the outer function"); + function innerFunction() { + console.log("This is the inner function"); + } + innerFunction(); +} + +outerFunction(); + +// Using built-in functions +function exampleMath() { + console.log("The absolute value of -5 is: " + Math.abs(-5)); +} + +exampleMath(); + +// Local and global variables +var globalVar = "I am a global variable"; + +function variableScope() { + var localVar = "I am a local variable"; + console.log(globalVar); + console.log(localVar); +} + +variableScope(); +console.log(globalVar); +// The following line will throw an error because 'localVar' is not defined in the global scope +// console.log(localVar); + +// Extra Exercise // + +function oneHundred(param1, param2) { + let counter = 0; + + for (let i = 1; i <= 100; i++) { + if (i % 3 === 0 && i % 5 === 0) { + console.log(param1, param2); + } else if (i % 3 === 0) { + console.log(param1); + } else if (i % 5 === 0) { + console.log(param2); + } else { + console.log(i); + counter++; + } + } + return counter; +} + +const counter = oneHundred('Fizz', 'Buzz'); +console.log("Count of numbers printed: " + counter); From d03ef7978f997de25cdc5f9adcb59199068bcc77 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:51:41 -0500 Subject: [PATCH 04/31] #03 - JavaScript --- .../javascript/Sac-Corts.js | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 Roadmap/03 - ESTRUCTURAS DE DATOS/javascript/Sac-Corts.js diff --git a/Roadmap/03 - ESTRUCTURAS DE DATOS/javascript/Sac-Corts.js b/Roadmap/03 - ESTRUCTURAS DE DATOS/javascript/Sac-Corts.js new file mode 100644 index 0000000000..4d6549d247 --- /dev/null +++ b/Roadmap/03 - ESTRUCTURAS DE DATOS/javascript/Sac-Corts.js @@ -0,0 +1,209 @@ +// Exercise // + +// Arrays +let array = [1, 2, 3, 4, 5]; + +array.push(6); +array.unshift(0); +array.splice(3, 0, 2.5); +console.log(array); + +array.pop(); +array.shift(); +array.splice(3, 1); +console.log(array); + +array[2] = 9; +console.log(array); + +array.sort((a, b) => a - b); +console.log(array); + +// Objects +let obj = { + name: 'Isaac', + age: 22, + city: 'Reynosa' +}; + +obj.country = "México"; +console.log(obj); + +delete obj.city; +console.log(obj); + +obj.age = 23; +console.log(obj); + +let sortedKeys = Object.keys(obj).sort(); +let sortedObj = {}; +for (let key of sortedKeys) { + sortedObj[key] = obj[key]; +} +console.log(sortedObj); + +// Sets +let set = new Set([2, 3, 5, 1, 4]); + +set.add(6); +console.log(set); + +set.delete(3); +console.log(set); + +let sortedSet = new Set([...set].sort((a, b) => a - b)); +console.log(sortedSet); + +// Maps +let map = new Map([ + ["name", "Isaac"], + ["age", 22], + ["city", "Reynosa"] +]); + +map.set("country", "México"); +console.log(map); + +map.delete("city"); +console.log(map); + +map.set("age", 23); +console.log(map); + +let sortedMapArray = [...map.entries()].sort(); +let sortedMap = new Map(sortedMapArray); +console.log(sortedMap); + +// WeakSets +let weakSet = new WeakSet(); +let obj1 = { a: 1 }; +let obj2 = { b: 2 }; + +weakSet.add(obj1); +weakSet.add(obj2); + +weakSet.delete(obj1); +console.log(weakSet); + +// WeakMaps +let weakMap = new WeakMap(); +let key1 = {}; +let key2 = {}; + +weakMap.set(key1, "value1"); +weakMap.set(key2, "value2") + +weakMap.delete(key1); + +weakMap.set(key2, "newValue2"); +console.log(weakMap); + +// Extra Exercise // + +const readline = require('readline'); + +const rl = readline.createInterface( + process.stdin, process.stdout); + + +let contactBook = []; + +function menu() { + console.log(` + 1. Search contact + 2. Add contact + 3. Update contact + 4. Delete contact + 5. Exit + `); + rl.question('Select an option: ', handleUserInput); +} + +function handleUserInput(option) { + switch(option) { + case '1': + searchContact(); + break; + case '2': + addContact(); + break; + case '3': + updateContact(); + break; + case '4': + deleteContact(); + break; + case '5': + rl.close(); + break; + default: + console.log('Invalid option'); + menu(); + } +} + +function searchContact() { + rl.question("Enter the contact's username: ", (name) => { + const contact = contactBook.find(c => c.name.toLowerCase() === name.toLowerCase()); + if (contact) { + console.log(`Contact found: ${contact.name} - ${contact.phone}`); + } else { + console.log('Contact not found'); + } + menu(); + }); +} + +function addContact() { + rl.question("Enter the contact's username: ", (name) => { + rl.question("Enter the contact's phone number: ", (phone) => { + if (/^\d{1,11}$/.test(phone)) { + contactBook.push({name, phone}); + console.log('Contact added'); + } else { + console.log('Invalid phone number'); + } + menu(); + }); + }); +} + +function updateContact() { + rl.question("Enter the name of the contact to update: ", (name) => { + const contact = contactBook.find(c => c.name.toLowerCase() === name.toLowerCase()); + if (contact) { + rl.question("Enter the new phone number: ", (phone) => { + if (/^\d{1,11}$/.test(phone)) { + contact.phone = phone; + console.log('Contact updated'); + } else { + console.log('Invalid phone number'); + } + menu(); + }); + } else { + console.log('Contact not found'); + menu(); + } + }); +} + +function deleteContact() { + rl.question("Enter the name of the contact to delete: ", (name) => { + const index = contactBook.findIndex(c => c.name.toLowerCase() === name.toLowerCase()); + if (index !== -1) { + contactBook.splice(index, 1); + console.log('Contact deleted'); + } else { + console.log('Contact not found'); + } + menu(); + }); +} + +rl.on('close', () => { + console.log('Finished program') + process.exit(0); +}); + +menu(); \ No newline at end of file From 07d88935ec093bdf8bbc1832bda84e41b9a01dc3 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:52:00 -0500 Subject: [PATCH 05/31] #04 - JavaScript --- .../javascript/Sac-Corts.js | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 Roadmap/04 - CADENAS DE CARACTERES/javascript/Sac-Corts.js diff --git a/Roadmap/04 - CADENAS DE CARACTERES/javascript/Sac-Corts.js b/Roadmap/04 - CADENAS DE CARACTERES/javascript/Sac-Corts.js new file mode 100644 index 0000000000..cdfa10c1a9 --- /dev/null +++ b/Roadmap/04 - CADENAS DE CARACTERES/javascript/Sac-Corts.js @@ -0,0 +1,105 @@ +// Ejercicio // + +// Accessing specific characters +let str = "Hello World"; +console.log(str[0]); +console.log(str.charAt(6)); + +// Substrings +console.log(str.substring(0, 5)); +console.log(str.slice(6)); +console.log(str.slice(-5)); + +// Length +console.log(str.length); + +// Concatenation +let str1 = "Hello"; +let str2 = "World"; +console.log(str1 + " " + str2); +console.log(str1.concat(" ", + str2)); + +// Repetition +console.log(str.repeat(3)); + +// Iteration +for (let char of str) { + console.log(char); +} + +// Conversion to uppercase and lowercase +console.log(str.toUpperCase()); +console.log(str.toLowerCase()); + +// Replacement +console.log(str.replace("World", "Everyone")); + +// Splitting +let words = str.split(" "); +console.log(words); + +// Joining +let joinedStr = words.join(" "); +console.log(joinedStr); + +// Interpolation +let _name = "Isaac"; +let greeting = `Hello ${_name}!`; +console.log(greeting); + +// Checking substrings +console.log(str.includes("World")); +console.log(str.startsWith("Hello")); +console.log(str.endsWith("World")); + +// Trimming +let paddedStr = " Hello World "; +console.log(paddedStr.trim()); +console.log(paddedStr.trimStart()); +console.log(paddedStr.trimEnd()); + +// Converting to array of characters +console.log(Array.from(str)); + +// Finding character of substring position +console.log(str.indexOf("o")); +console.log(str.lastIndexOf("o")); + +// Extra Exercise // + +function checkPalindrome(word) { + let inverted = word.split('').reverse().join(''); + return word === inverted; +} + +function checkAnagram(word1, word2) { + let ordered1 = word1.split('').sort().join(''); + let ordered2 = word2.split('').sort().join(''); + return ordered1 === ordered2; +} + +function checkIsogram(word) { + let letters = new Set([]); + for (char of word) { + if (letters.has(char)) { + return false; + } + letters.add(char); + } + return true; +} + +function checkWords(word1, word2) { + return { + word1ItsPalindrome: checkPalindrome(word1), + word2ItsPalindrome: checkPalindrome(word2), + theyAreAnagrams: checkAnagram(word1, word2), + word1ItsIsogram: checkIsogram(word1), + word2ItsIsogram: checkIsogram(word2), + }; +} + +let word1 = "civic"; +let word2 = "radar"; + +console.log(checkWords(word1, word2)); From c772573ccdee31915c3e7aa91a34944223118ebe Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:52:20 -0500 Subject: [PATCH 06/31] #05 - JavaScript --- .../javascript/Sac-Corts.js | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Roadmap/05 - VALOR Y REFERENCIA/javascript/Sac-Corts.js diff --git a/Roadmap/05 - VALOR Y REFERENCIA/javascript/Sac-Corts.js b/Roadmap/05 - VALOR Y REFERENCIA/javascript/Sac-Corts.js new file mode 100644 index 0000000000..71528e9009 --- /dev/null +++ b/Roadmap/05 - VALOR Y REFERENCIA/javascript/Sac-Corts.js @@ -0,0 +1,69 @@ +// Exercise // + +// Variable Assignment +// By value +let a = 10; +let b = a; +b = 20; + +console.log(a); +console.log(b); + +// By reference +let obj1 = { value: 10 }; +let obj2 = obj1; +obj2.value = 20; + +console.log(obj1.value); +console.log(obj2.value); + +// Passing from Parameters to Functions +// By value +function changeValue(x) { + x = 30; + return x; +} + +let num = 10; +console.log(changeValue(num)); +console.log(num); + +// By reference +function changeObj(obj) { + obj.value = 60; + return obj; +} + +let myObj = { value: 50 }; +console.log(changeObj(myObj)); +console.log(myObj); + +// Extra Exercise // +let str1 = "Hello"; +let str2 = "World"; + +// By value +function swapByValue(x, y) { + let temp = x; + x = y; + y = temp; + return [x, y]; +} + +// By reference +function swapByReference(ref) { + let temp = ref.str1; + ref.str1 = ref.str2; + ref.str2 = temp; +} + +let [newStr1, newStr2] = swapByValue(str1, str2); +console.log("Swap by value:"); +console.log("Original values: str1 = ", str1, " str2 = ", str2); +console.log("New values: nweStr1 = ", newStr1, " newStr2 = ", newStr2); + +let ref = {str1: str1, str2: str2}; +swapByReference(ref); +console.log("Swap by reference"); +console.log("Original values: str1 = ", str1, " str2 = ", str2); +console.log("New values: ref.str1 = ", ref.str1, " ref.str2 = ", ref.str2); \ No newline at end of file From 343814cd646b0b1811c852f13c748c0fd0bcf1ce Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:52:37 -0500 Subject: [PATCH 07/31] #06 - JavaScript --- .../06 - RECURSIVIDAD/javascript/Sac-Corts.js | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Roadmap/06 - RECURSIVIDAD/javascript/Sac-Corts.js diff --git a/Roadmap/06 - RECURSIVIDAD/javascript/Sac-Corts.js b/Roadmap/06 - RECURSIVIDAD/javascript/Sac-Corts.js new file mode 100644 index 0000000000..d385293508 --- /dev/null +++ b/Roadmap/06 - RECURSIVIDAD/javascript/Sac-Corts.js @@ -0,0 +1,32 @@ +// Exercise // +function from100to0(n) { + if (n <= 0) { + return 0; + } + console.log(n); + return from100to0(n - 1); +} + +console.log(from100to0(100)); + +// Extra Exercise // +function factorial(n) { + if (n <= 1) { + return 1; + } + return n * factorial(n - 1); +} + +console.log(factorial(5)); + +function fibonacci(n) { + if (n == 1) { + return 1; + } else if (n == 0) { + return 0; + } else { + return fibonacci(n-1) + fibonacci(n-2); + } +} + +console.log(fibonacci(2)); From 6869d2c4039c057277332ad961db97bc45f6f1d5 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:53:02 -0500 Subject: [PATCH 08/31] #07 - JavaScript --- .../javascript/Sac-Corts.js | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 Roadmap/07 - PILAS Y COLAS/javascript/Sac-Corts.js diff --git a/Roadmap/07 - PILAS Y COLAS/javascript/Sac-Corts.js b/Roadmap/07 - PILAS Y COLAS/javascript/Sac-Corts.js new file mode 100644 index 0000000000..a31b8b7291 --- /dev/null +++ b/Roadmap/07 - PILAS Y COLAS/javascript/Sac-Corts.js @@ -0,0 +1,188 @@ +// Exercise // +class Stack { + constructor() { + this.items = []; + } + + push(element) { + this.items.push(element); + } + + pop() { + if (this.isEmpty()) { + return "Stack is empty"; + } + return this.items.pop(); + } + + peek() { + if (this.isEmpty()) { + return "Stack is empty"; + } + return this.items[this.items.length - 1]; + } + + isEmpty() { + return this.items.length === 0; + } + + size() { + return this.items.length; + } +} + +const stack = new Stack(); +stack.push(11); +stack.push(7); +stack.push(21); +console.log(stack.peek()); +console.log(stack.pop()); +console.log(stack.size()); +console.log(stack.isEmpty()); + +class Queue { + constructor() { + this.items = []; + } + + enqueue(element) { + this.items.push(element); + } + + dequeue() { + if (this.isEmpty()) { + return "Queue is empty"; + } + return this.items.shift(); + } + + front() { + if (this.isEmpty()) { + return "Queue is empty"; + } + return this.items[0]; + } + + isEmpty() { + return this.items.length === 0; + } + + size() { + return this.items.length; + } +} + +const queue = new Queue(); +queue.enqueue(11); +queue.enqueue(7); +queue.enqueue(21); +console.log(queue.front()); +console.log(queue.dequeue()); +console.log(queue.size()); +console.log(queue.isEmpty()); + +// Extra Exercise // + +// Browser History +const readline = require('readline'); + +class BrowserHistory { + constructor() { + this.record = []; + this.forward = []; + } + + navigateTo(page) { + this.record.push(page); + this.forward.length = 0; + console.log(`Current page: ${page}`); + } + + goBack() { + if (this.record.length > 1) { + const lastPage = this.record.pop(); + this.forward.push(lastPage); + console.log(`Current page: ${this.record[this.record.length - 1]}`); + } else { + console.log("There are no more pages"); + } + } + + goForward() { + if (this.forward.length) { + const nextPage = this.forward.pop(); + this.record.push(nextPage); + console.log(`Current page: ${nextPage}`) + } else { + console.log("There are no more pages"); + } + } +} + +// Printer +class Printer { + constructor() { + this.queue = []; + } + + addDocument(document) { + this.queue.push(document); + } + + printDocument() { + if (this.queue.length > 0) { + const print = this.queue.shift(); + console.log(`Printing ${print} | Remaining queue: ${this.queue}`); + } else { + console.log("There are no prints at the moment."); + } + } +} + +const myHistory = new BrowserHistory(); +const myPrinter = new Printer(); + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +// Functions to control the browser history and the printer +function historyControl() { + rl.question("Enter a page or 'backward'/'forward' ('exit' to finish): ", (command) => { + command = command.toLowerCase(); + if (command === 'backward') { + myHistory.goBack(); + } else if (command === 'forward') { + myHistory.goForward(); + } else if (command === 'hexit') { + console.log("Exiting the browser..."); + printerControl(); + return; + } else { + myHistory.navigateTo(command); + } + + historyControl(); + }); +} + + +function printerControl() { + rl.question("Enter a document or 'print' (if you want to print a document in the queue): ", (command) => { + command = command.toLowerCase(); + if (command === 'print') { + myPrinter.printDocument(); + } else if (command === 'pexit') { + console.log("Turning off the printer..."); + rl.close(); + } else { + myPrinter.addDocument(command); + console.log(`Print queue: ${myPrinter.queue}`); + } + + printerControl(); + }); +} + +historyControl(); \ No newline at end of file From 544016fda70347a3ba88f6347c2cf98c17362a1f Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:53:20 -0500 Subject: [PATCH 09/31] #08 - JavaScript --- Roadmap/08 - CLASES/javascript/Sac-Corts.js | 106 ++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 Roadmap/08 - CLASES/javascript/Sac-Corts.js diff --git a/Roadmap/08 - CLASES/javascript/Sac-Corts.js b/Roadmap/08 - CLASES/javascript/Sac-Corts.js new file mode 100644 index 0000000000..571f414f3c --- /dev/null +++ b/Roadmap/08 - CLASES/javascript/Sac-Corts.js @@ -0,0 +1,106 @@ +// Exercise +class Person { + constructor(name, age) { + this.name = name; + this.age = age; + } + + greet() { + console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); + } +} + +isaac = new Person('Isaac', 22); +isaac.greet(); + +isaac.name = 'Isaac Cortés'; +isaac.age = 23; +isaac.greet(); + +// Extra Exercise // +class Stack { + constructor() { + this.array = []; + } + + push(item) { + this.array.push(item); + } + + pop() { + if (this.isEmpty()) { + return "Stack is empty."; + } + return this.array.pop(); + } + + peek() { + if (this.isEmpty()) { + return "Stack is empty."; + } + return this.array[this.array.length - 1]; + } + + isEmpty() { + return this.array.length === 0; + } + + size() { + return this.array.length; + } +} + +const stack = new Stack(); +stack.push('Karina'); +stack.push('Isaac'); +stack.push('Danna'); +console.log(stack.peek()); +console.log(stack.pop()); +console.log(stack.isEmpty()); +console.log(stack.size()); + + +class Queue{ + constructor() { + this.array = []; + } + + enqueue(item) { + this.array.push(item); + } + + dequeue() { + if (this.isEmpty()) { + return "Queue is empty." + } + return this.array.shift(); + } + + front() { + if (this.isEmpty()) { + return "Queue is empty." + } + return this.array[0]; + } + + isEmpty() { + return this.array.length === 0; + } + + size() { + return this.array.length; + } +} + +const queue = new Queue(); +queue.enqueue('Marco'); +queue.enqueue('Ceci'); +queue.enqueue('Jenni'); +console.log(queue.front()); +console.log(queue.dequeue()); +console.log(queue.isEmpty()); +console.log(queue.size()); + + + + From fc256a040f44dd0b9e439a4610d78d3732591bdc Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:53:46 -0500 Subject: [PATCH 10/31] #09 - JavaScript --- Roadmap/09 - HERENCIA/javascript/Sac-Corts.js | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 Roadmap/09 - HERENCIA/javascript/Sac-Corts.js diff --git a/Roadmap/09 - HERENCIA/javascript/Sac-Corts.js b/Roadmap/09 - HERENCIA/javascript/Sac-Corts.js new file mode 100644 index 0000000000..3e37d6ddc6 --- /dev/null +++ b/Roadmap/09 - HERENCIA/javascript/Sac-Corts.js @@ -0,0 +1,127 @@ +// Exercise +class Animal { + constructor(name) { + this.name = name; + } + + sound() { + console.log(`${this.name} makes a sound`); + } +} + +class Dog extends Animal { + constructor(name) { + super(name); + } + + sound() { + console.log('gua gua gua!'); + } +} + +class Cat extends Animal { + constructor(name) { + super(name); + } + + sound() { + console.log('miau miau miau!') + } +} + +function makeASound(animal) { + animal.sound(); +} + +const myDog = new Dog('Junior'); +const myCat = new Cat ('Luna'); + +makeASound(myDog); +makeASound(myCat); + +// Extra Exercise // +class Employee { + constructor(name, id) { + this.name = name; + this.id = id; + this.employeesInCharge = []; + } + + addEmployee(employee) { + this.employeesInCharge.push(employee); + } + + showInformation() { + console.log(`ID: ${this.id}`); + console.log(`Name: ${this.name}`); + if (this.employeesInCharge.length > 0) { + console.log("Employees in charge:"); + this.employeesInCharge.forEach((employee) => { + employee.showInformation(); + }); + } + } +} + +class Manager extends Employee { + constructor(name, id, deparment) { + super(name, id); + this.deparment = deparment; + } + + assignEmployee(employee) { + this.addEmployee(employee); + } + + showInformation() { + super.showInformation(); + console.log(`Deparment: ${this.deparment}`); + } +} + +class ProjectManager extends Manager { + constructor(name, id, deparment, currentProject) { + super(name, id, deparment); + this.currentProject = currentProject; + } + + assignProject(project) { + this.currentProject = project; + } + + showInformation() { + super.showInformation(); + console.log(`Current Project: ${this.currentProject}`); + } +} + +class Developer extends Employee { + constructor(name, id, languages, level) { + super(name, id); + this.languages = languages; + this.level = level; + } + + writeCode() { + console.log(`${this.name} is writing code in ${this.languages.join(", ")}`); + } + + showInformation() { + super.showInformation() + console.log(`Programming languages: ${this.languages.join(", ")}`); + console.log(`Level: ${this.level}`); + } +} + +const developer1 = new Developer('Angelo', '3', ['Python, JavaScript, Java, C'], 'Senior'); +const developer2 = new Developer('Isaac', '4', ['Python, JavaScript'], 'Junior'); +const projectManager = new ProjectManager('Luisa', '2', 'Web Development', 'Project IG'); +const manager = new Manager('Luis', '1', 'IT'); + +manager.assignEmployee(developer1); +projectManager.assignEmployee(developer2); +manager.assignEmployee(projectManager); +manager.showInformation(); +developer2.writeCode(); +projectManager.assignProject('Project X'); +manager.showInformation(); \ No newline at end of file From 525ba4a0b68830c573e62b35f399fe290d49074a Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:54:58 -0500 Subject: [PATCH 11/31] #10 -JavaScript --- .../10 - EXCEPCIONES/javascript/Sac-Corts.js | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Roadmap/10 - EXCEPCIONES/javascript/Sac-Corts.js diff --git a/Roadmap/10 - EXCEPCIONES/javascript/Sac-Corts.js b/Roadmap/10 - EXCEPCIONES/javascript/Sac-Corts.js new file mode 100644 index 0000000000..a436aff159 --- /dev/null +++ b/Roadmap/10 - EXCEPCIONES/javascript/Sac-Corts.js @@ -0,0 +1,53 @@ +// Exercise // +function divide(a, b) { + try { + if (b === 0) { + throw new Error("Cannot divide by 0."); + } + return a / b; + } catch (error) { + console.error('Error:', error.message); + } finally { + console.log("Division operation completed."); + } +} + +divide(10, 0); + +// Extra Exercise // +class CustomError extends Error { + constructor(message) { + super(message); + this.name = "CustomError"; + } +} + +function processParameters(param) { + try { + if (param < 0) { + throw new RangeError("The parameter must not be negative."); + } + if (typeof param !== 'number') { + throw new TypeError("The parameter must be a number"); + } + if (param === 0) { + throw new CustomError("The parameter must no be zero"); + } + return `The parameter ${param} was processed correctly.` + } catch (error) { + console.error(`Caught error: ${error.name} - ${error.message}`); + throw error; + } +} + +try { + let result = processParameters("Hi"); + console.log(result); + console.log("No error occurred."); +} catch (error) {} finally { + console.log("The execution ended."); +} + + + + From 250e032fff5334e0a42495a7384b81640005081e Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:55:17 -0500 Subject: [PATCH 12/31] #11 - JavaScript --- .../javascript/Sac-Corts.js | 167 ++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 Roadmap/11 - MANEJO DE FICHEROS/javascript/Sac-Corts.js diff --git a/Roadmap/11 - MANEJO DE FICHEROS/javascript/Sac-Corts.js b/Roadmap/11 - MANEJO DE FICHEROS/javascript/Sac-Corts.js new file mode 100644 index 0000000000..e0a4b2e8fe --- /dev/null +++ b/Roadmap/11 - MANEJO DE FICHEROS/javascript/Sac-Corts.js @@ -0,0 +1,167 @@ +// Exercise // +const fs = require('fs'); +const readline = require('readline'); + +const userName = "Sac-Corts"; +const name = "Isaac"; +const age = 22; +const favoriteLanguage = "JavaScript"; + +const fileName = `${userName}.txt`; + +fs.writeFileSync(fileName, `Name: ${name}\n`); +fs.appendFileSync(fileName, `Age: ${age}\n`); +fs.appendFileSync(fileName, `Favorite programming language: ${favoriteLanguage}\n`); + +const content = fs.readFileSync(fileName, 'utf8'); +console.log(content); + +fs.unlinkSync(fileName); + +// Extra Exercise // + +const file = 'products.txt'; + +const readData = () => { + try { + const data = fs.readFileSync(file, 'utf8'); + return data.split('\n').filter(line => line.trim() !== ''); + } catch (err) { + return []; + } +}; + +const writeData = (data) => { + fs.writeFileSync(file, data.join('\n'), 'utf8'); +}; + +const addProduct = (name, quantity, price) => { + const data = readData(); + data.push(`${name}, ${quantity}, ${price}`); + writeData(data); + console.log('Product added successfully.'); +}; + +const viewProduct = (name) => { + const data = readData(); + const product = data.find(line => line.startsWith(name)); + if (product) { + console.log(`Product found: ${product}`); + } else { + console.log('Product not found.'); + } +}; + +const updateProduct = (name, quantity, price) => { + const data = readData(); + const index = data.findIndex(line => line.startsWith(name)); + if (index !== -1) { + data[index] = `${name}, ${quantity}, ${price}`; + writeData(data); + console.log('Product updated successfully.'); + } else { + console.log('Product not found.'); + } +}; + +const deleteProduct = (name) => { + const data = readData(); + const newData = data.filter(line => !line.startsWith(name)); + if (data.length !== newData.length) { + writeData(newData); + console.log('Product deleted successfully.'); + } else { + console.log('Product not found.'); + } +}; + +const calculateTotalSales = () => { + const data = readData(); + let total = 0; + data.forEach(line => { + const [, quantity, price] = line.split(', '); + total += parseInt(quantity) * parseFloat(price); + }); + console.log(`Total sales: ${total.toFixed(2)}`); +}; + +const calculateProductSales = (name) => { + const data = readData(); + const product = data.find(line => line.startsWith(name)); + if (product) { + const [, quantity, price] = product.split(', '); + const sales = parseInt(quantity) * parseFloat(price); + console.log(`Sales for ${name}: ${sales.toFixed(2)}`); + } else { + console.log('Product not found.'); + } +}; + +const clearFile = () => { + fs.unlinkSync(file); + console.log('File cleared.'); +}; + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +const main = () => { + rl.question('Choose an option: (add/view/update/delete/total/individual/exit) ', (option) => { + switch (option.toLowerCase()) { + case 'add': + rl.question('Enter product name: ', (name) => { + rl.question('Enter quantity sold: ', (quantity) => { + rl.question('Enter price: ', (price) => { + addProduct(name, quantity, price); + main(); + }); + }); + }); + break; + case 'view': + rl.question('Enter product name: ', (name) => { + viewProduct(name); + main(); + }); + break; + case 'update': + rl.question('Enter product name: ', (name) => { + rl.question('Enter new quantity sold: ', (quantity) => { + rl.question('Enter new price: ', (price) => { + updateProduct(name, quantity, price); + main(); + }); + }); + }); + break; + case 'delete': + rl.question('Enter product name: ', (name) => { + deleteProduct(name); + main(); + }); + break; + case 'total': + calculateTotalSales(); + main(); + break; + case 'individual': + rl.question('Enter product name: ', (name) => { + calculateProductSales(name); + main(); + }); + break; + case 'exit': + clearFile(); + rl.close(); + break; + default: + console.log('Invalid option. Please try again.'); + main(); + break; + } + }); +}; + +main(); \ No newline at end of file From cdec3951f6322162132f87087e2f7b41e198affb Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:55:33 -0500 Subject: [PATCH 13/31] #12 - JavaScript --- .../12 - JSON Y XML/javascript/Sac-Corts.js | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Roadmap/12 - JSON Y XML/javascript/Sac-Corts.js diff --git a/Roadmap/12 - JSON Y XML/javascript/Sac-Corts.js b/Roadmap/12 - JSON Y XML/javascript/Sac-Corts.js new file mode 100644 index 0000000000..0da19f786b --- /dev/null +++ b/Roadmap/12 - JSON Y XML/javascript/Sac-Corts.js @@ -0,0 +1,101 @@ +const fs = require('fs'); + +const data = { + name: 'Isaac Cortés', + age: 22, + birthdate: "2001-10-21", + programmingLanguage: ["JavaScript", "Python"] +}; + +fs.writeFileSync('data.json', JSON.stringify(data, null, 4)); + +let xmlData2 = ` + + ${data.name} + ${data.age} + ${data.birthdate} + ${data.programmingLanguage.map(lang => `${lang}`).join('\n ')} +`; + +fs.writeFileSync('data.xml', xmlData2); + +console.log("Content of data.json:"); +console.log(fs.readFileSync('data.json', 'utf8')); + +console.log("\nContent of data.xml:"); +console.log(fs.readFileSync('data.xml', 'utf8')); + +// fs.unlinkSync('data.json'); +// fs.unlinkSync('data.xml'); +// console.log("\nDeleted Files."); + + +// Extra Exercise // + +class Person { + constructor(name, age, birthdate, programmingLanguage) { + this.name = name; + this.age = age; + this.birthdate = birthdate; + this.programmingLanguage = programmingLanguage; + } + + showData() { + console.log(`Name: ${this.name}`); + console.log(`Age: ${this.age}`); + console.log(`Birthdate: ${this.birthdate}`); + console.log(`Programming Language: ${this.programmingLanguage.join(', ')}`); + + } +} + +// Read JSON and XML file +const jsonContent = fs.readFileSync('data.json', 'utf-8'); +const xmlContent = fs.readFileSync('data.xml', 'utf-8'); + +// Parse JSON and XML in JavaScript +const jsonData = JSON.parse(jsonContent); + +function parseXML(xml) { + const name = xml.match(/(.*?)<\/name>/)[1]; + const age = parseInt(xml.match(/(.*?)<\/age>/)[1], 10); + const birthdate = xml.match(/(.*?)<\/birthdate>/)[1]; + const languagesMatches = xml.match(/(.*?)<\/language>/g); + const programmingLanguage = languagesMatches.map(lang => lang.replace(/<\/?language>/g, '')); + + return { + name, + age, + birthdate, + programmingLanguage + }; +} + +const xmlData = parseXML(xmlContent); + +// Create instances of the class with the read data +const personFromJson = new Person( + jsonData.name, + jsonData.age, + jsonData.birthdate, + jsonData.programmingLanguage +); + +const personFromXml = new Person( + xmlData.name, + xmlData.age, + xmlData.birthdate, + xmlData.programmingLanguage +); + +// Show data for class instances +console.log("Data from JSON:"); +personFromJson.showData(); + +console.log("\nData from XML:"); +personFromXml.showData(); + +// Delete the files +fs.unlinkSync('data.json'); +fs.unlinkSync('data.xml'); +console.log("\nDeleted files."); \ No newline at end of file From 7ef9d0448918f65916ab8daccd3bec14c92afc58 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:56:11 -0500 Subject: [PATCH 14/31] #13 - JavaScript --- .../javascript/Sac-Corts.js | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Roadmap/13 - PRUEBAS UNITARIAS/javascript/Sac-Corts.js diff --git a/Roadmap/13 - PRUEBAS UNITARIAS/javascript/Sac-Corts.js b/Roadmap/13 - PRUEBAS UNITARIAS/javascript/Sac-Corts.js new file mode 100644 index 0000000000..6c8f555359 --- /dev/null +++ b/Roadmap/13 - PRUEBAS UNITARIAS/javascript/Sac-Corts.js @@ -0,0 +1,39 @@ +// npm install --save-dev jest +// We name the file with the ending .test.js + +function addition(a, b) { + return a + b; +} + +test('addition 1 + 2 should be 3', () => { + expect(addition(1, 2)).toBe(3); +}); + +test('addition 3 + 7 should be 10', () => { + expect(addition(3, 7)).toBe(10); +}); + +// To run the program: npx jest .\Sac-Corts.test.js + +// Extra Exercise + +const data = { + name: "Isaac", + age: "22", + birthdate: "2001-10-21", + programmingLanguages: ["JavaScript", "Python"] +} + +test('It should have all the necessary keys', () => { + expect(data).toHaveProperty('name'); + expect(data).toHaveProperty('age'); + expect(data).toHaveProperty('birthdate'); + expect(data).toHaveProperty('programmingLanguages'); +}); + +test('It should have the correct data', () => { + expect(data.name).toBe("Isaac"); + expect(data.age).toBe("22"); + expect(data.birthdate).toBe("2001-10-21"); + expect(data.programmingLanguages).toEqual(["JavaScript", "Python"]); +}); \ No newline at end of file From fc7d05087740b59a625b8835c9054ce8155bb9b4 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:56:31 -0500 Subject: [PATCH 15/31] #14 - JavaScript --- Roadmap/14 - FECHAS/javascript/Sac-Corts.js | 51 +++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Roadmap/14 - FECHAS/javascript/Sac-Corts.js diff --git a/Roadmap/14 - FECHAS/javascript/Sac-Corts.js b/Roadmap/14 - FECHAS/javascript/Sac-Corts.js new file mode 100644 index 0000000000..3662ec721b --- /dev/null +++ b/Roadmap/14 - FECHAS/javascript/Sac-Corts.js @@ -0,0 +1,51 @@ +const currentDate = new Date(); +const birthdate = new Date('2001-10-21T08:30:00'); + +function calculateAge(currentDate, birthdate) { + let age = currentDate.getFullYear() - birthdate.getFullYear(); + const month = currentDate.getMonth() - birthdate.getMonth(); + + if (month < 0 || (month === 0 && currentDate.getDate() < birthdate.getDate())) { + age--; + } + + return age; +} + +const age = calculateAge(currentDate, birthdate); +console.log(`${age} years have passed since the date of birth`); + +// Extra Exercise // +const dayMonthYear = birthdate.toLocaleDateString('es-ES'); + +const hourMinuteSecond = birthdate.toLocaleTimeString('es-ES'); + +const startYear = new Date(birthdate.getFullYear(), 0, 0); +const difference = birthdate - startYear; +const oneDay = 1000 * 60 * 60 * 24; +const dayOfTheYear = Math.floor(difference / oneDay); + +const dayOfTheWeek = birthdate.toLocaleDateString('es-ES', { weekday: 'long' }); + +const nameMonth = birthdate.toLocaleDateString('es-ES', { month: 'long' }); + +const longDate = birthdate.toLocaleDateString('es-ES', { year: 'numeric', month: 'long', day: 'numeric' }); + +const formatISO = birthdate.toISOString(); + +const formatUTC = birthdate.toUTCString(); + +const timeUnix = birthdate.getTime(); + +const abbreviatedDate = birthdate.toLocaleDateString('es-ES', { weekday: 'short', month: 'short', day: 'numeric' }); + +console.log('Day, month and year:', dayMonthYear); +console.log('Hour, minute and second:', hourMinuteSecond); +console.log('Day of the year:', dayOfTheYear); +console.log('Day of the week:', dayOfTheWeek); +console.log('Name of the month:', nameMonth); +console.log('Long date:', longDate); +console.log('Format ISO:', formatISO); +console.log('Format UTC:', formatUTC); +console.log('Time in milliseconds since 1970:', timeUnix); +console.log('Abbreviated date:', abbreviatedDate); \ No newline at end of file From 38ed9fefd3bee7ba846ef0b37514cf5c4bc365ae Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:56:46 -0500 Subject: [PATCH 16/31] #15 - JavaScript --- .../javascript/Sac-Corts.js" | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 "Roadmap/15 - ASINCRON\303\215A/javascript/Sac-Corts.js" diff --git "a/Roadmap/15 - ASINCRON\303\215A/javascript/Sac-Corts.js" "b/Roadmap/15 - ASINCRON\303\215A/javascript/Sac-Corts.js" new file mode 100644 index 0000000000..91ace4c9a6 --- /dev/null +++ "b/Roadmap/15 - ASINCRON\303\215A/javascript/Sac-Corts.js" @@ -0,0 +1,47 @@ +async function runAsyncTask(taskName, durationInSeconds) { + console.log(`${taskName} start.`); + console.log(`Duration: ${durationInSeconds} seconds.`); + + const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + + await wait(durationInSeconds * 1000); + + console.log(`${taskName} ends.`); +} + +//runAsyncTask('Task 1', 3); +//runAsyncTask('Task 2', 6); + +// Extra Exercise // + +function delay(durationInSeconds, functionName) { + return new Promise((resolve) => { + setTimeout(() => { + console.log(`${functionName} has ended after ${durationInSeconds} seconds.`); + resolve(); + }, durationInSeconds * 1000); + }); +} + +async function functionA() { + await delay(1, 'Function A'); +} + +async function functionB() { + await delay(2, 'Function B'); +} + +async function functionC() { + await delay(3, 'Function C'); +} + +async function functionD() { + await delay(1, 'Function D'); +} + +async function executeFunctionsInOrder() { + await Promise.all([functionC(), functionB(), functionA()]); + await functionD(); +} + +executeFunctionsInOrder(); \ No newline at end of file From 01cdf83c1fee5d6b2893c76846e5feeaaf09ec7c Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:57:06 -0500 Subject: [PATCH 17/31] #16 - JavaScript --- .../javascript/Sac-Corts.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Roadmap/16 - EXPRESIONES REGULARES/javascript/Sac-Corts.js diff --git a/Roadmap/16 - EXPRESIONES REGULARES/javascript/Sac-Corts.js b/Roadmap/16 - EXPRESIONES REGULARES/javascript/Sac-Corts.js new file mode 100644 index 0000000000..4d4bf5ec2f --- /dev/null +++ b/Roadmap/16 - EXPRESIONES REGULARES/javascript/Sac-Corts.js @@ -0,0 +1,16 @@ +const text = "There are 3 cats, 7 dogs and 15 birds in the park."; +const numbers = text.match(/\d+/g) || []; +console.log(numbers); + +// Extra Exercise // +const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; +const email = "isaac@gmail.com"; +console.log(emailPattern.test(email)); + +const telPattern = /^\d{3}-\d{3}-\d{4}$/; +const number = "899-112-5641"; +console.log(telPattern.test(number)); + +const urlPattern = /^(https?:\/\/)?([\da-z.-]+\.[a-z.]{2,6}|[\d.]+)(:[0-9]{1,5})?(\/[\w.-]*)*\/?(\?[\w=&]*)?(#[\w-]*)?$/i; +const url = "https://retosdeprogramacion.com/roadmap/" +console.log(urlPattern.test(url)); \ No newline at end of file From a12e8355926fe05db883cce9daa1a3ada93aba44 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 02:57:31 -0500 Subject: [PATCH 18/31] #17 - JavaScript --- .../17 - ITERACIONES/javascript/Sac-Corts.js | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Roadmap/17 - ITERACIONES/javascript/Sac-Corts.js diff --git a/Roadmap/17 - ITERACIONES/javascript/Sac-Corts.js b/Roadmap/17 - ITERACIONES/javascript/Sac-Corts.js new file mode 100644 index 0000000000..b67fc0e84e --- /dev/null +++ b/Roadmap/17 - ITERACIONES/javascript/Sac-Corts.js @@ -0,0 +1,58 @@ +console.log("for"); +for (i = 1; i <= 10; i++) { + console.log(i); +} + +console.log("while"); +let n = 1; +while (n <= 10) { + console.log(n); + n++; +} + +console.log("do while"); +n = 1; +do { + console.log(n); + n++; +} while (n <= 10); + +// Extra Exercise // +console.log("for of"); +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +for (number of numbers) { + console.log(number); +} + +console.log("for in"); +for (number in numbers) { + console.log(numbers[number]); +} + +console.log("forEach"); +numbers.forEach((number) => { + console.log(number); +}); + +console.log("map"); +numbers.map((number) => { + console.log(number); +}); + +console.log("Array.from"); +Array.from({ length: 10 }, (_, i) => console.log(i + 1)); + +console.log("reduce"); +numbers.reduce((_, number) => { + console.log(number); + return number; +}, 0); + +console.log("Recursion"); +function printNumbers(n) { + if (n > 10) return; + console.log(n); + printNumbers(n + 1); +} + +printNumbers(1); \ No newline at end of file From 31956098a655fc600371365b8ed1ffd8816e7ca7 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Mon, 2 Sep 2024 04:13:27 -0500 Subject: [PATCH 19/31] #18 - JavaScript --- .../18 - CONJUNTOS/javascript/Sac-Corts.js | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Roadmap/18 - CONJUNTOS/javascript/Sac-Corts.js diff --git a/Roadmap/18 - CONJUNTOS/javascript/Sac-Corts.js b/Roadmap/18 - CONJUNTOS/javascript/Sac-Corts.js new file mode 100644 index 0000000000..ece5d64dd8 --- /dev/null +++ b/Roadmap/18 - CONJUNTOS/javascript/Sac-Corts.js @@ -0,0 +1,35 @@ +let set = []; +set.push(10); +set.unshift(1); +set.push(11, 12); +set.splice(1, 0, 2, 3); +set.splice(2, 1); +set[2] = 5; +let elementExist = set.includes(3); +console.log(elementExist); +console.log(set); +set = []; +console.log(set); + +// Extra Exercise // +const setA = new Set([1, 2, 3]); +const setB = new Set([3, 4, 5]); + +// Union +const union = new Set([...setA, ...setB]); +console.log(union); + +// Intersection +const intersection = new Set([...setA].filter(x => setB.has(x))); +console.log(intersection); + +// Difference +const difference = new Set([...setA].filter(x => !setB.has(x))); +console.log(difference); + +// Symmetric Difference +const symmetricDifference = new Set([ + ...[...setA].filter(x => !setB.has(x)), + ...[...setB].filter(x => !setA.has(x)) +]); +console.log(symmetricDifference); \ No newline at end of file From 556c8e25a973c44bbaa96511738b4e9e51b67799 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Thu, 5 Sep 2024 06:24:10 -0500 Subject: [PATCH 20/31] #19 - JavaScript --- .../javascript/Sac-Corts.js | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Roadmap/19 - ENUMERACIONES/javascript/Sac-Corts.js diff --git a/Roadmap/19 - ENUMERACIONES/javascript/Sac-Corts.js b/Roadmap/19 - ENUMERACIONES/javascript/Sac-Corts.js new file mode 100644 index 0000000000..12fdeed5e4 --- /dev/null +++ b/Roadmap/19 - ENUMERACIONES/javascript/Sac-Corts.js @@ -0,0 +1,74 @@ +const DaysOfWeek = { + 1: "Monday", + 2: "Tuesday", + 3: "Wednesday", + 4: "Thursday", + 5: "Friday", + 6: "Saturday", + 7: "Sunday" +}; + +function getDayName(dayNumber) { + return DaysOfWeek[dayNumber] || "Invalid day number"; +} + +console.log(getDayName(1)); +console.log(getDayName(7)); +console.log(getDayName(8)); + +// Extra Exercise // +const OrderStatus = { + PENDING: "pending", + SENT: "sent", + DELIVERED: "delivered", + CANCELED: "canceled" +} + +class Order { + constructor(id) { + this.id = id; + this.status = OrderStatus.PENDING; + } + + sendOrder() { + if (this.status === OrderStatus.PENDING) { + this.status = OrderStatus.SENT; + console.log(`Order ${this.id} has been sent.`); + } else { + console.log(`Order ${this.id} cannot be sent in status ${this.status}.`); + } + } + + cancelOrder() { + if (this.status === OrderStatus.DELIVERED) { + console.log(`Order ${this.id} cannot be canceled, because it has already been delivered.`); + } else { + this.status = OrderStatus.CANCELED; + console.log(`Order ${this.id} has been canceled.`); + } + } + + deliverOrder() { + if (this.status === OrderStatus.SENT) { + this.status = OrderStatus.DELIVERED; + console.log(`Order ${this.id} has been delivered`); + } else { + console.log(`Order ${this.id} cannot be delivered in status ${this.status}`); + } + } + + showStatus() { + console.log(`Order ${this.id} status is ${this.status}`); + } +} + +const order1 = new Order(1); +order1.showStatus(); +order1.sendOrder(); +order1.deliverOrder(); +order1.cancelOrder(); + +const order2 = new Order(2); +order2.sendOrder(); +order2.cancelOrder(); +order2.showStatus(); \ No newline at end of file From ed70524e2837a54b3ec88b21e11106736bb52c24 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Thu, 5 Sep 2024 06:25:24 -0500 Subject: [PATCH 21/31] #20 - JavaScript --- .../javascript/Sac-Corts.js | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Roadmap/20 - PETICIONES HTTP/javascript/Sac-Corts.js diff --git a/Roadmap/20 - PETICIONES HTTP/javascript/Sac-Corts.js b/Roadmap/20 - PETICIONES HTTP/javascript/Sac-Corts.js new file mode 100644 index 0000000000..ec5a05d78b --- /dev/null +++ b/Roadmap/20 - PETICIONES HTTP/javascript/Sac-Corts.js @@ -0,0 +1,66 @@ +const id = 10; +const urljson = `https://jsonplaceholder.typicode.com/posts/${id}`; + +fetch(urljson) + .then(response => { + if (!response.ok) { + throw new Error("Request error: " + response.status); + } + return response.json(); + }) + .then(data => { + console.log(data); + }) + .catch(error => { + console.error("There was a problem with the request Fetch:", error); + }); + +// Extra Exercise // + +async function getPokemonInfo(pokemon) { + try { + const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon.toLowerCase()}`); + const pokemonData = await response.json(); + + console.log('Pokemon data:', pokemonData.forms[0]["name"]); + + console.log('Name:', pokemonData.name); + + console.log('ID:', pokemonData.id); + + console.log('Weight:', pokemonData.weight); + + console.log('Height:', pokemonData.height); + + console.log('Types:'); + pokemonData.types.forEach(type => { + console.log('-', type.type.name); + }); + + const speciesResponse = await fetch(pokemonData.species.url); + const speciesData = await speciesResponse.json(); + const evolutionChainUrl = speciesData.evolution_chain.url; + const evolutionChainResponse = await fetch(evolutionChainUrl); + const evolutionChainData = await evolutionChainResponse.json(); + + console.log('Evolution chain:'); + let evolutionChain = evolutionChainData.chain; + while (evolutionChain) { + console.log('-', evolutionChain.species.name); + evolutionChain = evolutionChain['evolves_to'][0]; + } + + console.log('Games in which it appears:'); + pokemonData.game_indices.forEach(game => { + console.log('-', game.version.name); + }); + + } catch (error) { + console.error('Error:', error.message); + } +} + +const pokemon = '3'; +getPokemonInfo(pokemon); + +// Thanks to cesar-ch \ No newline at end of file From 63c9620455c3e870ac05aa2f82eecaeb70f6cd85 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Thu, 5 Sep 2024 06:26:19 -0500 Subject: [PATCH 22/31] #21 - JavaScript --- .../21 - CALLBACKS/javascript/Sac-Corts.js | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Roadmap/21 - CALLBACKS/javascript/Sac-Corts.js diff --git a/Roadmap/21 - CALLBACKS/javascript/Sac-Corts.js b/Roadmap/21 - CALLBACKS/javascript/Sac-Corts.js new file mode 100644 index 0000000000..0f2df2c45a --- /dev/null +++ b/Roadmap/21 - CALLBACKS/javascript/Sac-Corts.js @@ -0,0 +1,42 @@ +function greet(name, callback) { + console.log('Hi' + ' ' + name); + callback(); +} + +function callMe() { + console.log('I am callback function'); +} + +greet('Isaac', callMe); + +// Extra Exercise // +function processOrder(dish, confirmation, ready, delivery) { + setTimeout(() => { + console.log(`Order confirmed: ${dish}`); + confirmation(dish); + + setTimeout(() => { + console.log(`The dish ${dish} is ready.`); + ready(dish); + + setTimeout(() => { + console.log(`The dish ${dish} has been delivered.`); + delivery(dish); + }, Math.random() * 9000 + 1000); + }, Math.random() * 9000 + 1000); + }, Math.random() * 9000 + 1000); +} + +function confirmDish(dish) { + console.log(`Processing order: ${dish}`); +} + +function readyDish(dish) { + console.log(`Preparing the dish: ${dish}`); +} + +function deliverDish(dish) { + console.log(`Delivering the dish: ${dish}`); +} + +processOrder('Pizza', confirmDish, readyDish, deliverDish); \ No newline at end of file From 88a6f2d01966442202c2b9aac0f1af5514e142ef Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Thu, 5 Sep 2024 06:26:45 -0500 Subject: [PATCH 23/31] #22 - JavaScript --- .../javascript/Sac-Corts.js | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Roadmap/22 - FUNCIONES DE ORDEN SUPERIOR/javascript/Sac-Corts.js diff --git a/Roadmap/22 - FUNCIONES DE ORDEN SUPERIOR/javascript/Sac-Corts.js b/Roadmap/22 - FUNCIONES DE ORDEN SUPERIOR/javascript/Sac-Corts.js new file mode 100644 index 0000000000..88558b2fa5 --- /dev/null +++ b/Roadmap/22 - FUNCIONES DE ORDEN SUPERIOR/javascript/Sac-Corts.js @@ -0,0 +1,75 @@ +// Function that accepts another function as an argument +function processArray(func, arr) { + return arr.map(func); +} + +function square(x) { + return x * x; +} + +const numbers = [1, 2, 3, 4]; +const squares = processArray(square, numbers); +console.log(squares); + +// Function that returns another function +function createSum(x) { + return function(y) { + return x + y; + }; +} + +const sum5 = createSum(5); +console.log(sum5(20)); + +// Using filter, map and reduce +const numbers10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +const evenNumbers = numbers10.filter(num => num % 2 === 0); +const evenSquares = evenNumbers.map(num => num * num); +const sumEvenSquares = evenSquares.reduce((total, num) => total + num, 0); + +console.log(evenNumbers); +console.log(evenSquares); +console.log(sumEvenSquares); + +// Extra Exercise // + +const students = [{ + name: 'Isaac', + birthdate: new Date(2001, 9, 21), + qualifications: [9.0, 10, 9.5, 9.8] +}, +{ + name: 'Juan', + birthdate: new Date(2001, 6, 22), + qualifications: [9, 8, 8.5, 9.5] +}, +{ + name: 'Luis', + birthdate: new Date(2003, 10, 5), + qualifications: [6, 7, 7.5, 8] +}, +{ + name: 'María', + birthdate: new Date(2000, 4, 20), + qualifications: [10, 9.5, 10, 10] +}]; + +const studentAverage = students.map(student => { + const average = student.qualifications.reduce((sum, score) => sum + score, 0) / student.qualifications.length; + return { name: student.name, average: average.toFixed(2) }; +}); +console.log(studentAverage); + +const bestStudents = studentAverage.filter(student => student.average >= 9); +console.log(bestStudents); + +const datesOfBirthInOrder = students.sort((a, b) => b.birthdate - a.birthdate); +datesOfBirthInOrder.forEach(student => { + const date = student.birthdate; + console.log(`\n${student.name}: ${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`); +}); + +const allQualifications = students.flatMap(students => students.qualifications); +const highestScore = Math.max(...allQualifications); + +console.log(`\nThe highest score is ${highestScore}`); \ No newline at end of file From b2454d4e796437f67131ad6891bc4a6696b5e7f9 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Thu, 5 Sep 2024 06:29:41 -0500 Subject: [PATCH 24/31] #23 - JavaScript --- .../23 - SINGLETON/javascript/Sac-Corts.js | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Roadmap/23 - SINGLETON/javascript/Sac-Corts.js diff --git a/Roadmap/23 - SINGLETON/javascript/Sac-Corts.js b/Roadmap/23 - SINGLETON/javascript/Sac-Corts.js new file mode 100644 index 0000000000..f059307fa9 --- /dev/null +++ b/Roadmap/23 - SINGLETON/javascript/Sac-Corts.js @@ -0,0 +1,72 @@ +class Singleton { + constructor() { + if (Singleton.instance) { + return Singleton.instance; + } + this.data = "Singleton instance data"; + Singleton.instance = this; + return this; + } + + getData() { + return this.data; + } + + static getInstance() { + if(!Singleton.instance) { + Singleton.instance = new Singleton(); + } + return Singleton.instance; + } +} + +const instance1 = Singleton.getInstance(); +console.log(instance1.getData()); + +const instance2 = new Singleton(); +console.log(instance1 === instance2); + +// Extra Exercise // + +class UserSession { + constructor() { + if (UserSession.instance) { + return UserSession.instance; + } + this.user = null; + UserSession.instance = this; + return this; + } + + static getInstance() { + if (!UserSession.instance) { + UserSession.instance = new UserSession(); + } + return UserSession.instance; + } + + setUser(id, username, name, email) { + this.user = { id, username, name, email }; + } + + getUser() { + if (!this.user) { + return "There is no user in the session" + } + return this.user; + } + + clearSession() { + this.user = null; + } +} + +const session1 = UserSession.getInstance(); +session1.setUser(1, "Sac", "Isaac", "isaac@gmail.com"); +console.log(session1.getUser()); + +const session2 = UserSession.getInstance(); +console.log(session1 === session2); + +session2.clearSession(); +console.log(session1.getUser()); From 72d0b61230d190a278eca435329bb0cbe4444b21 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Thu, 5 Sep 2024 06:29:55 -0500 Subject: [PATCH 25/31] #24 - JavaScript --- .../24 - DECORADORES/javascript/Sac-Corts.js | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Roadmap/24 - DECORADORES/javascript/Sac-Corts.js diff --git a/Roadmap/24 - DECORADORES/javascript/Sac-Corts.js b/Roadmap/24 - DECORADORES/javascript/Sac-Corts.js new file mode 100644 index 0000000000..1fb892ddac --- /dev/null +++ b/Roadmap/24 - DECORADORES/javascript/Sac-Corts.js @@ -0,0 +1,32 @@ +function greet(name) { + return `Hello, ${name}!`; +} + +function logDecorator(fn) { + return function(...args) { + console.log(`Calling function: ${fn.name}`); + const result = fn(...args); + console.log(`Function ${fn.name} executed with result: ${result}`); + return result; + }; +} + +const decoratedGreet = logDecorator(greet); +console.log(decoratedGreet("Isaac")); + +// Extra Exercise // +function callCountDecorator(fn) { + let count = 0; + + return function(...args) { + count++; + console.log(`Function ${fn.name} has been called ${count} times`); + return fn(...args); + }; +} + +const decoratedGreet2 = callCountDecorator(greet); +console.log(decoratedGreet2("Hiel")); +console.log(decoratedGreet2("Kurama")); +console.log(decoratedGreet2("Yusuke")); +console.log(decoratedGreet2("Kuwabara")); \ No newline at end of file From 4b964159534d9526e11e900b5ee8167153081e3b Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Thu, 5 Sep 2024 06:30:18 -0500 Subject: [PATCH 26/31] #25 - JavaScript --- Roadmap/25 - LOGS/javascript/Sac-Corts.js | 60 +++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Roadmap/25 - LOGS/javascript/Sac-Corts.js diff --git a/Roadmap/25 - LOGS/javascript/Sac-Corts.js b/Roadmap/25 - LOGS/javascript/Sac-Corts.js new file mode 100644 index 0000000000..203657daf8 --- /dev/null +++ b/Roadmap/25 - LOGS/javascript/Sac-Corts.js @@ -0,0 +1,60 @@ +console.log("This is a general message"); +console.info("This is an infomational message"); +console.warn("Warning: This is a warning message"); +console.error("Error: This is an error message"); +console.debug("Debug: This is a debug message"); + +// Extra Exercise // +class TaskManager { + constructor() { + this.tasks = []; + } + + addTask(name, description) { + console.time(`addTask`); + console.log(`Trying add task: ${name}`); + + this.tasks.push({name, description}) + + console.info(`Task "${name}" added successfully`); + console.timeEnd(`addTask`); + } + + removeTask(name) { + console.time(`removeTask`); + console.log(`Trying remove task: ${name}`); + + const index = this.tasks.findIndex(task => task.name === name); + + if (index !== -1) { + this.tasks.splice(index, 1); + console.info(`Task "${name}" removed successfully`); + } else { + console.warn(`The task with the name "${name}" was not found`); + } + console.timeEnd(`removeTask`); + } + + listTasks() { + console.time(`listTasks`); + console.log(`Showing all tasks:`); + + if (this.tasks.length === 0) { + console.warn("No tasks available"); + } else { + this.tasks.forEach(task => { + console.info(`Task: ${task.name}, Description: ${task.description}`); + }); + } + console.timeEnd(`listTasks`); + } +} + +const taskManager = new TaskManager(); +taskManager.addTask("Task 1", "Do something"); +taskManager.addTask("Task 2", "Do anything"); + +taskManager.listTasks(); + +taskManager.removeTask("Task 2"); +console.log(taskManager); \ No newline at end of file From 6e279eeb2f4f9aca84956b042d1d6c6d87148552 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Sat, 7 Sep 2024 04:44:10 -0500 Subject: [PATCH 27/31] #26 - JavaScript --- .../26 - SOLID SRP/javascript/Sac-Corts.js | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 Roadmap/26 - SOLID SRP/javascript/Sac-Corts.js diff --git a/Roadmap/26 - SOLID SRP/javascript/Sac-Corts.js b/Roadmap/26 - SOLID SRP/javascript/Sac-Corts.js new file mode 100644 index 0000000000..b51ab81286 --- /dev/null +++ b/Roadmap/26 - SOLID SRP/javascript/Sac-Corts.js @@ -0,0 +1,120 @@ +// Invalid way +class User { + constructor(name, email) { + this.name = name; + this.email = email; + } + + getUserInfo() { + return { + name: this.name, + email: this.email + }; + } + + formatUserInfo() { + return `Name: ${this.name}, Email: ${this.email}`; + } +} + +const user = new User('Isaac Morales', 'isaac@gmail.com'); +console.log(user.formatUserInfo()); + +// Correct way +class UserInfo { + constructor(name, email) { + this.name = name; + this.email = email; + } + + getUserInfo() { + return { + name: this.name, + email: this.email + }; + } +} + +class FormatUser { + static format(user) { + return `Name: ${user.name}, Email: ${user.email}`; + } +} + +const newUser = new UserInfo('Isaac Cortés', 'isaac@gmail.com'); +console.log(FormatUser.format(newUser)); + +// Extra Exercise // +class BookManager { + constructor() { + this.books = []; + } + + addBook(title, author, copies) { + this.books.push({ title, author, copies }); + } + + findBook(title) { + return this.books.find(book => book.title === title); + } +} + +class UserManager { + constructor() { + this.users = []; + } + + addUser(name, id, email) { + this.users.push({ name, id, email }); + } + + findUser(id) { + return this.users.find(user => user.id === id); + } +} + +class LoanManager { + constructor(bookManager, userManager) { + this.bookManager = bookManager; + this.userManager = userManager; + this.loans = []; + } + + borrowBook(userId, bookTitle) { + const user = this.userManager.findUser(userId); + const book = this.bookManager.findBook(bookTitle); + + if (user && book && book.copies > 0) { + book.copies--; + this.loans.push({ userId, bookTitle }); + console.log(`${user.name} borrowed "${book.title}"`); + } else { + console.log(`Book is unavailable or user not found`); + } + } + + returnBook(userId, bookTitle) { + const loanIndex = this.loans.findIndex( + loan => loan.userId === userId && loan.bookTitle === bookTitle + ); + const book = this.bookManager.findBook(bookTitle); + + if (loanIndex !== -1 && book) { + book.copies++; + this.loans.splice(loanIndex, 1); + console.log(`"${book.title}" has been returned`); + } else { + console.log('Loan not found or book not available'); + } + } +} + +const bookManager = new BookManager(); +const userManager = new UserManager(); +const loanManager = new LoanManager(bookManager, userManager); + +bookManager.addBook('The Great Gatsby', 'F. Scott Fitzgerald', 5); +userManager.addUser('Isaac', 1, 'isaac@gmail.com'); + +loanManager.borrowBook(1, 'The Great Gatsby'); +loanManager.returnBook(1, 'The Great Gatsby'); From 5ce1ffbd198bca570805509b300dd02c8a410055 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Sat, 7 Sep 2024 04:44:59 -0500 Subject: [PATCH 28/31] #27 - JavaScript --- .../27 - SOLID OCP/javascript/Sac-Corts.js | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 Roadmap/27 - SOLID OCP/javascript/Sac-Corts.js diff --git a/Roadmap/27 - SOLID OCP/javascript/Sac-Corts.js b/Roadmap/27 - SOLID OCP/javascript/Sac-Corts.js new file mode 100644 index 0000000000..7b29ca394a --- /dev/null +++ b/Roadmap/27 - SOLID OCP/javascript/Sac-Corts.js @@ -0,0 +1,123 @@ +// Wrong way +class ShapeCalculator { + calculateArea(shape) { + if (shape.type === 'circle'){ + return Math.PI * Math.pow(shape.radius, 2); + } else if (shape.type === 'square') { + return Math.pow(shape.side, 2); + } else { + throw new Error('Shape not supported'); + } + } +} + +const calculator = new ShapeCalculator(); +console.log(calculator.calculateArea({ type: 'circle', radius: 5 })); +console.log(calculator.calculateArea({ type: 'square', side: 4 })); + +// Correct way +class Shape { + calculateArea(shape) { + throw new Error('calculateArea() must be implemented'); + } +} + +class Circle extends Shape { + constructor(radius) { + super(); + this.radius = radius; + } + + calculateArea() { + return Math.PI * Math.pow(this.radius, 2); + } +} + +class Square extends Shape { + constructor(side) { + super(); + this.side = side; + } + + calculateArea() { + return Math.pow(this.side, 2); + } +} + +function printArea(shape) { + console.log(`Area: ${shape.calculateArea()}`); +} + +const circle = new Circle(5); +const square = new Square(4); +printArea(circle); +printArea(square); + +// Extra Exercise // +class Operation { + calculate(a, b) { + throw new Error('calculateOperation() must be implemented'); + } +} + +class Addition extends Operation { + calculate(a, b) { + return a + b; + } +} + +class Subtraction extends Operation { + calculate(a, b) { + return a - b; + } +} + +class Multiplication extends Operation { + calculate(a, b) { + return a * b; + } +} + +class Division extends Operation { + calculate(a, b) { + if (b === 0) throw new Error('Division by zero is not allowed'); + return a / b; + } +} + +class Pow extends Operation { + calculate(a, b) { + return Math.pow(a, b); + } +} + +class Calculator { + constructor() { + this.operations = {}; + } + + addOperation(name, operation) { + this.operations[name] = operation; + } + + calculate(name, a, b) { + const operation = this.operations[name]; + if (!operation) throw new Error(`Operation "${name}" not supported`); + return operation.calculate(a, b); + } +} + +const calculator2 = new Calculator(); +calculator2.addOperation('addition', new Addition()); +calculator2.addOperation('subtraction', new Subtraction()); +calculator2.addOperation('multiplication', new Multiplication()); +calculator2.addOperation('division', new Division()); +calculator2.addOperation('pow', new Pow()); + +console.log(calculator2.calculate('addition', 2, 10)); +console.log(calculator2.calculate('subtraction', 2, 10)); +console.log(calculator2.calculate('multiplication', 2, 10)); +console.log(calculator2.calculate('division', 10, 5)); +console.log(calculator2.calculate('pow', 10, 2)); + + From cb90521e77dfb0074a998e5797db991946b6cf70 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Sat, 7 Sep 2024 04:45:17 -0500 Subject: [PATCH 29/31] #28 - JavaScript --- .../28 - SOLID LSP/javascript/Sac-Corts.js | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 Roadmap/28 - SOLID LSP/javascript/Sac-Corts.js diff --git a/Roadmap/28 - SOLID LSP/javascript/Sac-Corts.js b/Roadmap/28 - SOLID LSP/javascript/Sac-Corts.js new file mode 100644 index 0000000000..ad2d6c09ed --- /dev/null +++ b/Roadmap/28 - SOLID LSP/javascript/Sac-Corts.js @@ -0,0 +1,105 @@ +// Wrong way +class Bird { + fly() { + console.log('Flying!'); + } +} + +class Penguin extends Bird { + fly() { + throw new Error('Penguins cannot fly!'); + } +} + +function makeBirdFly(bird) { + bird.fly(); +} + +const bird = new Bird(); +const penguin = new Penguin(); + +makeBirdFly(bird); +// makeBirdFly(penguin); // Not working // + +// Correct way +class Bird2 { + eat() { + console.log('Eating...'); + } +} + +class FlyingBird extends Bird2 { + fly() { + console.log('Flying!'); + } +} + +class Penguin2 extends Bird2 { + swin() { + console.log('Swimming!'); + } +} + +function makeFlyingBirdFly(bird) { + bird.fly(); +} + +const eagle = new FlyingBird(); +const penguin2 = new Penguin2(); + +makeFlyingBirdFly(eagle); +// makeBirdFly(penguin); // Not working // + +// Extra Exercise // +class Vehicle { + accelerate() { + throw new Error('accelerate() must be implemented'); + } + + brake() { + throw new Error('brake() must be implemented'); + } +} + +class Car extends Vehicle { + accelerate() { + console.log('Car is accelerating'); + } + + brake() { + console.log('Car is braking'); + } +} + +class Motorcycle extends Vehicle { + accelerate() { + console.log('Motorcycle is accelerating'); + } + + brake() { + console.log('Motorcycle is braking'); + } +} + +class Bicycle extends Vehicle { + accelerate() { + console.log('Bicycle is accelerating'); + } + + brake() { + console.log('Bicycle is braking'); + } +} + +function testVehicle(vehicle) { + vehicle.accelerate(); + vehicle.brake(); +} + +const car = new Car(); +const motorcycle = new Motorcycle(); +const bicycle = new Bicycle(); + +testVehicle(car); +testVehicle(motorcycle); +testVehicle(bicycle); From 7c94744b124efaf36601bdcac8e4fc1c53f82c48 Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Sat, 7 Sep 2024 04:45:44 -0500 Subject: [PATCH 30/31] #29 - JavaScript --- .../29 - SOLID ISP/javascript/Sac-Corts.js | 157 ++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 Roadmap/29 - SOLID ISP/javascript/Sac-Corts.js diff --git a/Roadmap/29 - SOLID ISP/javascript/Sac-Corts.js b/Roadmap/29 - SOLID ISP/javascript/Sac-Corts.js new file mode 100644 index 0000000000..84aa8d61dd --- /dev/null +++ b/Roadmap/29 - SOLID ISP/javascript/Sac-Corts.js @@ -0,0 +1,157 @@ +// Wrong way +class Device { + turnOn() {} + turnOff() {} + charge() {} + connectToInternet() {} +} + +class Laptop extends Device { + turnOn() { + console.log("Laptop turned on"); + } + + turnOff() { + console.log("Laptop turned off"); + } + + charge() { + console.log("Laptop charging"); + } + + connectToInternet() { + console.log("Laptop connected to the internet"); + } +} + +class Microwave extends Device { + turnOn() { + console.log("Microwave turned on"); + } + + turnOff() { + console.log("Microwave turned off"); + } + + charge() { + throw new Error("A microwave doesn't need to be charged"); + } + + connectToInternet() { + throw new Error("A microwave doesn't need to be connected to the internet"); + } +} + +const microwave = new Microwave(); +// microwave.charge(); // Error + +// Correct way +class Switchable { + turnOn() {} + turnOff() {} +} + +class Chargeable { + charge() {} +} + +class InternetConnectable { + connectToInternet() {} +} + +class Laptop2 extends Switchable { + turnOn() { + console.log("Laptop turned on"); + } + + turnOff() { + console.log("Laptop turned off"); + } +} + +class AdvancedLaptop extends Laptop2 { + charge() { + console.log("Laptop charging."); + } + + connectToInternet() { + console.log("Laptop connected to the internet."); + } +} + +class Microwave2 extends Switchable { + turnOn() { + console.log("Microwave turned on"); + } + + turnOff() { + console.log("Microwave turned off"); + } +} + +const laptop2 = new AdvancedLaptop(); +laptop2.charge(); +laptop2.connectToInternet(); + +const microwave2 = new Microwave2(); +microwave2.turnOn(); +microwave2.turnOff(); + +// Extra Exercise // +class BlackAndWhitePrintable { + printBlackAndWhite() {} +} + +class ColorPrintable { + printColor() {} +} + +class Scannable { + scan() {} +} + +class Faxable { + sendFax() {} +} + +class BlackAndWhitePrinter extends BlackAndWhitePrintable { + printBlackAndWhite() { + console.log("Printing in black and white..."); + } +} + +class ColorPrinter extends ColorPrintable { + printColor() { + console.log("Printing in color..."); + } +} + +class MultiFunctionPrinter extends BlackAndWhitePrintable { + printBlackAndWhite() { + console.log("Printing in black and white..."); + } + + printColor() { + console.log("Printing in color..."); + } + + scan() { + console.log("Scanning..."); + } + + sendFax() { + console.log("Sending fax..."); + } +} + +const blackAndWhitePrinter = new BlackAndWhitePrinter(); +blackAndWhitePrinter.printBlackAndWhite(); + +const colorPrinter = new ColorPrinter(); +colorPrinter.printColor(); + +const multiFunctionPrinter = new MultiFunctionPrinter(); +multiFunctionPrinter.printBlackAndWhite(); +multiFunctionPrinter.printColor(); +multiFunctionPrinter.scan(); +multiFunctionPrinter.sendFax(); \ No newline at end of file From db49317a1c0cb7965d1486877f8f84337cd290cd Mon Sep 17 00:00:00 2001 From: Sac-Corts Date: Sat, 7 Sep 2024 04:45:59 -0500 Subject: [PATCH 31/31] #30 - JavaScript --- .../30 - SOLID DIP/javascript/Sac-Corts.js | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Roadmap/30 - SOLID DIP/javascript/Sac-Corts.js diff --git a/Roadmap/30 - SOLID DIP/javascript/Sac-Corts.js b/Roadmap/30 - SOLID DIP/javascript/Sac-Corts.js new file mode 100644 index 0000000000..058be0c299 --- /dev/null +++ b/Roadmap/30 - SOLID DIP/javascript/Sac-Corts.js @@ -0,0 +1,101 @@ +// Wrong way +class UserService { + constructor() { + this.database = new MySQLDatabase(); + } + + getUser(id) { + return this.database.findUserById(id); + } +} + +class MySQLDatabase { + findUserById(id) { + return { id, name: 'Isaac Cortés', db: 'MySQL' }; + } +} + +const userService = new UserService(); +console.log(userService.getUser(1)); + +// Correct way +class UserService2 { + constructor(database) { + this.database = database; + } + + getUser(id) { + return this.database.findUserById(id); + } +} + +class Database { + findUserById(id) { + throw new Error("Method not implemented"); + } +} + +class MySQLDatabase2 extends Database { + findUserById(id) { + return { id, name: 'Isaac Cortés', db: 'MySQL' }; + } +} + +class MongoDBDatabase extends Database { + findUserById(id) { + return { id, name: 'Isaac Cortés', db: 'MongoDB' }; + } +} + +const mysqlService = new UserService2(new MySQLDatabase2()); +console.log(mysqlService.getUser(1)); + +const mongoService = new UserService2(new MongoDBDatabase()); +console.log(mongoService.getUser(2)); + +// Extra Exercise // +class NotificationService { + sendNotification(message, recipient) { + throw new Error('Method not implemented'); + } +} + +class EmailNotification extends NotificationService { + sendNotification(message, recipient) { + console.log(`Sending email to ${recipient}: ${message}`); + } +} + +class PushNotification extends NotificationService { + sendNotification(message, recipient) { + console.log(`Sending push to ${recipient}: ${message}`); + } +} + +class SMSNotification extends NotificationService { + sendNotification(message, recipient) { + console.log(`Sending SMS to ${recipient}: ${message}`) + } +} + +class NotificationManager { + constructor(notificationService) { + this.notificationService = notificationService; + } + + send(message, recipient) { + this.notificationService.sendNotification(message, recipient); + } +} + +const emailService = new EmailNotification(); +const pushService = new PushNotification(); +const smsService = new SMSNotification(); + +const emailManager = new NotificationManager(emailService); +const pushManager = new NotificationManager(pushService); +const smsManager = new NotificationManager(smsService); + +emailManager.send('Hello, Isaac!', 'isaac@gmail.com'); +pushManager.send('Hello, Isaac!', 'sac'); +smsManager.send('Hello, Isaac!', '8992584897'); \ No newline at end of file