├── .gitignore ├── .DS_Store ├── Responsive Web Design ├── 8 - Responsive Web Design Projects │ └── 1 - Tribute Page │ │ ├── script.js │ │ ├── stylesheet.css │ │ └── index.html └── 1 - Basic HTML and HTML5 │ └── index.html ├── Responsive-Web-Design ├── 8 - Responsive Web Design Projects │ └── 1 - Tribute Page │ │ ├── script.js │ │ ├── stylesheet.css │ │ └── index.html └── 1 - Basic HTML and HTML5 │ └── index.html ├── .gitattributes ├── JavaScript Algorithms and Data Structures ├── 9 - Intermediate-Algorithm-Scripting-Challenges │ ├── .prettierrc.json │ └── .eslintrc.json ├── 4 - Debugging │ ├── catch-unclosed-parentheses-brackets-braces-and-quotes.js │ ├── use-typeof-to-check-the-type-of-a-variable.js │ ├── use-the-javascript-console-to-check-the-value-of-a-variable.js │ ├── catch-misspelled-variable-and-function-names.js │ ├── understanding-the-differences-between-the-freecodecamp-and-browser-console.js │ └── index.js ├── freecodeCamp-starting-from-08-31-2020 │ └── index.js ├── 6 - Basic Algorithm Scripting │ └── index.js ├── 5 - Basic-Data-Structures │ └── index.js ├── 7 - Object Oriented Programming │ └── index.js └── 3 - Regular-Expressions │ └── index.js └── JavaScript-Algorithms-and-Data-Structures ├── 9 - Intermediate-Algorithm-Scripting-Challenges ├── .prettierrc.json └── .eslintrc.json ├── 4 - Debugging ├── catch-unclosed-parentheses-brackets-braces-and-quotes.js ├── use-typeof-to-check-the-type-of-a-variable.js ├── use-the-javascript-console-to-check-the-value-of-a-variable.js ├── catch-misspelled-variable-and-function-names.js ├── understanding-the-differences-between-the-freecodecamp-and-browser-console.js └── index.js ├── 10 - JavaScript Algorithms and Data Structure Projects └── index.js ├── freecodeCamp-starting-from-08-31-2020 └── index.js ├── 6 - Basic Algorithm Scripting └── index.js ├── 5 - Basic-Data-Structures └── index.js ├── 7 - Object Oriented Programming └── index.js └── 3 - Regular-Expressions └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .DS_Store 3 | .DS_Store 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miguelmanalo/my-freeCodeCamp/HEAD/.DS_Store -------------------------------------------------------------------------------- /Responsive Web Design/8 - Responsive Web Design Projects/1 - Tribute Page/script.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Responsive-Web-Design/8 - Responsive Web Design Projects/1 - Tribute Page/script.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/9 - Intermediate-Algorithm-Scripting-Challenges/.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "singleQuote": true, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/9 - Intermediate-Algorithm-Scripting-Challenges/.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "singleQuote": true, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/4 - Debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.js: -------------------------------------------------------------------------------- 1 | // Debugging: Catch Unclosed Parentheses, Brackets, Braces and Quotes 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes 3 | 4 | // Fix the two pair errors in the code. 5 | 6 | let myArray = [1, 2, 3]; 7 | let arraySum = myArray.reduce((previous, current) => previous + current); 8 | console.log(`Sum of array values is: ${arraySum}`); 9 | -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/4 - Debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.js: -------------------------------------------------------------------------------- 1 | // Debugging: Catch Unclosed Parentheses, Brackets, Braces and Quotes 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes 3 | 4 | // Fix the two pair errors in the code. 5 | 6 | let myArray = [1, 2, 3]; 7 | let arraySum = myArray.reduce((previous, current) => previous + current); 8 | console.log(`Sum of array values is: ${arraySum}`); 9 | -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/4 - Debugging/use-typeof-to-check-the-type-of-a-variable.js: -------------------------------------------------------------------------------- 1 | // Debugging: Use typeof to Check the Type of a Variable 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable 3 | 4 | // Add two console.log() statements to check the typeof each of the two variables seven and three in the code. 5 | 6 | let seven = 7; 7 | let three = "3"; 8 | console.log(seven + three); 9 | // Only change code below this line 10 | console.log(typeof seven); 11 | console.log(typeof three); -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/4 - Debugging/use-typeof-to-check-the-type-of-a-variable.js: -------------------------------------------------------------------------------- 1 | // Debugging: Use typeof to Check the Type of a Variable 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable 3 | 4 | // Add two console.log() statements to check the typeof each of the two variables seven and three in the code. 5 | 6 | let seven = 7; 7 | let three = "3"; 8 | console.log(seven + three); 9 | // Only change code below this line 10 | console.log(typeof seven); 11 | console.log(typeof three); -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/4 - Debugging/use-the-javascript-console-to-check-the-value-of-a-variable.js: -------------------------------------------------------------------------------- 1 | // Debugging: Use the JavaScript Console to Check the Value of a Variable 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable 3 | 4 | // Use the console.log() method to print the value of the variable a where noted in the code. 5 | 6 | let a = 5; 7 | let b = 1; 8 | a++; 9 | // Only change code below this line 10 | console.log(a); 11 | 12 | let sumAB = a + b; 13 | console.log(sumAB); 14 | -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/4 - Debugging/use-the-javascript-console-to-check-the-value-of-a-variable.js: -------------------------------------------------------------------------------- 1 | // Debugging: Use the JavaScript Console to Check the Value of a Variable 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable 3 | 4 | // Use the console.log() method to print the value of the variable a where noted in the code. 5 | 6 | let a = 5; 7 | let b = 1; 8 | a++; 9 | // Only change code below this line 10 | console.log(a); 11 | 12 | let sumAB = a + b; 13 | console.log(sumAB); 14 | -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/4 - Debugging/catch-misspelled-variable-and-function-names.js: -------------------------------------------------------------------------------- 1 | // Debugging: Catch Misspelled Variable and Function Names 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-misspelled-variable-and-function-names 3 | 4 | // Fix the two spelling errors in the code so the netWorkingCapital calculation works. 5 | 6 | // let receivables = 10; 7 | // let payables = 8; 8 | // let netWorkingCapital = recievables - payable; 9 | // console.log(`Net working capital is: ${netWorkingCapital}`); 10 | 11 | let receivables = 10; 12 | let payables = 8; 13 | let netWorkingCapital = receivables - payables; 14 | console.log(`Net working capital is: ${netWorkingCapital}`); 15 | -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/4 - Debugging/catch-misspelled-variable-and-function-names.js: -------------------------------------------------------------------------------- 1 | // Debugging: Catch Misspelled Variable and Function Names 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-misspelled-variable-and-function-names 3 | 4 | // Fix the two spelling errors in the code so the netWorkingCapital calculation works. 5 | 6 | // let receivables = 10; 7 | // let payables = 8; 8 | // let netWorkingCapital = recievables - payable; 9 | // console.log(`Net working capital is: ${netWorkingCapital}`); 10 | 11 | let receivables = 10; 12 | let payables = 8; 13 | let netWorkingCapital = receivables - payables; 14 | console.log(`Net working capital is: ${netWorkingCapital}`); 15 | -------------------------------------------------------------------------------- /Responsive Web Design/8 - Responsive Web Design Projects/1 - Tribute Page/stylesheet.css: -------------------------------------------------------------------------------- 1 | body { 2 | background: #adb2d3; 3 | } 4 | 5 | h1 { 6 | text-align: center; 7 | font-family: sans-serif; 8 | } 9 | 10 | h2 { 11 | text-align: center; 12 | font-family: sans-serif; 13 | padding: 15px 0px 15px 0px; 14 | } 15 | 16 | p { 17 | text-align: center; 18 | font-family: sans-serif; 19 | } 20 | 21 | #img-div { 22 | text-align: center; 23 | font-family: sans-serif; 24 | } 25 | 26 | #img { 27 | max-width: 50%; 28 | height: auto; 29 | } 30 | 31 | ul { 32 | list-style-position: inside; 33 | text-align: center; 34 | font-family: sans-serif; 35 | } 36 | 37 | li { 38 | text-align: center; 39 | font-family: sans-serif; 40 | } 41 | 42 | .quote { 43 | 44 | } -------------------------------------------------------------------------------- /Responsive-Web-Design/8 - Responsive Web Design Projects/1 - Tribute Page/stylesheet.css: -------------------------------------------------------------------------------- 1 | body { 2 | background: #adb2d3; 3 | } 4 | 5 | h1 { 6 | text-align: center; 7 | font-family: sans-serif; 8 | } 9 | 10 | h2 { 11 | text-align: center; 12 | font-family: sans-serif; 13 | padding: 15px 0px 15px 0px; 14 | } 15 | 16 | p { 17 | text-align: center; 18 | font-family: sans-serif; 19 | } 20 | 21 | #img-div { 22 | text-align: center; 23 | font-family: sans-serif; 24 | } 25 | 26 | #img { 27 | max-width: 50%; 28 | height: auto; 29 | } 30 | 31 | ul { 32 | list-style-position: inside; 33 | text-align: center; 34 | font-family: sans-serif; 35 | } 36 | 37 | li { 38 | text-align: center; 39 | font-family: sans-serif; 40 | } 41 | 42 | .quote { 43 | 44 | } -------------------------------------------------------------------------------- /Responsive Web Design/1 - Basic HTML and HTML5/index.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 |

Header 1

28 |

subheader

29 | 30 | 31 | 32 |
-------------------------------------------------------------------------------- /Responsive-Web-Design/1 - Basic HTML and HTML5/index.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 |

Header 1

28 |

subheader

29 | 30 | 31 | 32 |
-------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/9 - Intermediate-Algorithm-Scripting-Challenges/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "airbnb", 4 | "plugin:prettier/recommended", 5 | "prettier/react" 6 | ], 7 | "env": { 8 | "browser": true, 9 | "commonjs": true, 10 | "es6": true, 11 | "jest": true, 12 | "node": true 13 | }, 14 | "rules": { 15 | "jsx-a11y/href-no-hash": ["off"], 16 | "react/jsx-filename-extension": ["warn", { "extensions": [".js", ".jsx"] }], 17 | "max-len": [ 18 | "warn", 19 | { 20 | "code": 80, 21 | "tabWidth": 2, 22 | "comments": 80, 23 | "ignoreComments": false, 24 | "ignoreTrailingComments": true, 25 | "ignoreUrls": true, 26 | "ignoreStrings": true, 27 | "ignoreTemplateLiterals": true, 28 | "ignoreRegExpLiterals": true 29 | } 30 | ] 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/9 - Intermediate-Algorithm-Scripting-Challenges/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "airbnb", 4 | "plugin:prettier/recommended", 5 | "prettier/react" 6 | ], 7 | "env": { 8 | "browser": true, 9 | "commonjs": true, 10 | "es6": true, 11 | "jest": true, 12 | "node": true 13 | }, 14 | "rules": { 15 | "jsx-a11y/href-no-hash": ["off"], 16 | "react/jsx-filename-extension": ["warn", { "extensions": [".js", ".jsx"] }], 17 | "max-len": [ 18 | "warn", 19 | { 20 | "code": 80, 21 | "tabWidth": 2, 22 | "comments": 80, 23 | "ignoreComments": false, 24 | "ignoreTrailingComments": true, 25 | "ignoreUrls": true, 26 | "ignoreStrings": true, 27 | "ignoreTemplateLiterals": true, 28 | "ignoreRegExpLiterals": true 29 | } 30 | ] 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/4 - Debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.js: -------------------------------------------------------------------------------- 1 | // Debugging: Understanding the Differences between the freeCodeCamp and Browser Console 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console 3 | 4 | // First, use console.log to log the output variable. Then, use console.clear to clear the browser console. 5 | 6 | // Open your browser console. 7 | let output = "Get this to log once in the freeCodeCamp console and twice in the browser console"; 8 | // Use console.log() to print the output variable. 9 | console.clear(); 10 | console.log(output); 11 | // Run the tests to see the difference between the two consoles. 12 | 13 | // Now, add console.clear() before your console.log() to clear the browser console, and pass the tests. 14 | -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/4 - Debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.js: -------------------------------------------------------------------------------- 1 | // Debugging: Understanding the Differences between the freeCodeCamp and Browser Console 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console 3 | 4 | // First, use console.log to log the output variable. Then, use console.clear to clear the browser console. 5 | 6 | // Open your browser console. 7 | let output = "Get this to log once in the freeCodeCamp console and twice in the browser console"; 8 | // Use console.log() to print the output variable. 9 | console.clear(); 10 | console.log(output); 11 | // Run the tests to see the difference between the two consoles. 12 | 13 | // Now, add console.clear() before your console.log() to clear the browser console, and pass the tests. 14 | -------------------------------------------------------------------------------- /Responsive Web Design/8 - Responsive Web Design Projects/1 - Tribute Page/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | A Tribute to Blank Blank 5 | 6 | 7 | 8 |
9 | 10 | 11 |

Blank Blank

12 |

Here is a subheading.

13 | 14 |
15 | 16 |

Description of photo above

17 |
18 | 19 |
20 |

Here's a time line of Blank Blank's life:

21 | 42 |
43 | 44 |
45 |

"Quote goes here."

46 |

--Person Who Said Quote

47 |
48 | 49 | 50 | 51 |
-------------------------------------------------------------------------------- /Responsive-Web-Design/8 - Responsive Web Design Projects/1 - Tribute Page/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | A Tribute to Blank Blank 5 | 6 | 7 | 8 |
9 | 10 | 11 |

Blank Blank

12 |

Here is a subheading.

13 | 14 |
15 | 16 |

Description of photo above

17 |
18 | 19 |
20 |

Here's a time line of Blank Blank's life:

21 | 42 |
43 | 44 |
45 |

"Quote goes here."

46 |

--Person Who Said Quote

47 |
48 | 49 | 50 | 51 |
-------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/10 - JavaScript Algorithms and Data Structure Projects/index.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable max-len */ 2 | /// ////////////////////////////////////////////////////////////////////// 3 | // Palindrome Checker 4 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker 5 | // Return true if the given string is a palindrome. Otherwise, return false. 6 | 7 | // A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing. 8 | 9 | // Note 10 | // You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes. 11 | 12 | // We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others. 13 | 14 | // We'll also pass strings with special symbols, such as "2A3*3a2", "2A3 3a2", and "2_A3*3#A2". 15 | 16 | function palindrome(str) { 17 | return true; 18 | } 19 | 20 | console.log(palindrome('eye')); // should return a boolean 21 | console.log(palindrome('eye')); // should return true 22 | console.log(palindrome('_eye')); // should return true 23 | console.log(palindrome('race car')); // should return true 24 | console.log(palindrome('not a palindrome')); // should return false 25 | console.log(palindrome('A man, a plan, a canal. Panama')); // should return true 26 | console.log(palindrome('never odd or even')); // should return true 27 | console.log(palindrome('nope')); // should return false 28 | console.log(palindrome('almostomla')); // should return false 29 | console.log(palindrome('My age is 0, 0 si ega ym.')); // should return true 30 | console.log(palindrome('1 eye for of 1 eye.')); // should return false 31 | console.log(palindrome('0_0 (: /- :) 0-0')); // should return true 32 | console.log(palindrome('five|_/|four')); // should return false 33 | -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/freecodeCamp-starting-from-08-31-2020/index.js: -------------------------------------------------------------------------------- 1 | // ES6: Create a Module Script 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-a-module-script 3 | 4 | {/* 5 | 6 | 7 | 8 | 9 | 10 | */} 11 | 12 | ///////////////////////////////////// 13 | 14 | // ES6: Use export to Share a Code Block 15 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-export-to-share-a-code-block 16 | 17 | export const uppercaseString = (string) => { 18 | return string.toUpperCase(); 19 | } 20 | 21 | const lowercaseString = (string) => { 22 | return string.toLowerCase() 23 | } 24 | 25 | export { lowercaseString } 26 | 27 | ///////////////////////////////////// 28 | 29 | // ES6: Reuse JavaScript Code Using import 30 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import 31 | 32 | import { uppercaseString, lowercaseString } from 'string_functions.js'; 33 | // Only change code above this line 34 | 35 | uppercaseString("hello"); 36 | lowercaseString("WORLD!"); 37 | 38 | ///////////////////////////////////// 39 | // ES6: Use * to Import Everything from a File 40 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file 41 | 42 | import * as stringFunctions from "./string_functions.js" 43 | 44 | // Only change code above this line 45 | 46 | stringFunctions.uppercaseString("hello"); 47 | stringFunctions.lowercaseString("WORLD!"); 48 | 49 | ///////////////////////////////////// 50 | 51 | // ES6: Create an Export Fallback with export default 52 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default 53 | 54 | export default function subtract(x, y) { 55 | return x - y; 56 | } 57 | 58 | 59 | https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-a-javascript-promise 60 | // ES6: Import a Default Export 61 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/import-a-default-export 62 | 63 | 64 | 65 | import subtract from "./math_functions.js" 66 | // Only change code above this line 67 | 68 | subtract(7,4); 69 | 70 | ///////////////////////////////////// 71 | 72 | // ES6: Create a JavaScript Promise 73 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-a-javascript-promise 74 | 75 | // promise syntax 76 | //const myPromise = new Promise((resolve, reject) => { 77 | 78 | // }); 79 | 80 | const makeServerRequest = new Promise((resolve, reject) => { 81 | 82 | }); 83 | 84 | 85 | ///////////////////////////////////// 86 | 87 | // ES6: Complete a Promise with resolve and reject 88 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/complete-a-promise-with-resolve-and-reject 89 | 90 | // const myPromise = new Promise((resolve, reject) => { 91 | // if(condition here) { 92 | // resolve("Promise was fulfilled"); 93 | // } else { 94 | // reject("Promise was rejected"); 95 | // } 96 | // }); 97 | 98 | const makeServerRequest = new Promise((resolve, reject) => { 99 | // responseFromServer represents a response from a server 100 | let responseFromServer; 101 | 102 | if(responseFromServer) { 103 | // Change this line 104 | resolve('We got the data'); 105 | } else { 106 | // Change this line 107 | reject('Data not received') 108 | } 109 | }); 110 | 111 | ///////////////////////////////////// 112 | 113 | // ES6: Handle a Fulfilled Promise with then 114 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/handle-a-fulfilled-promise-with-then 115 | 116 | // myPromise.then(result => { 117 | // // do something with the result. 118 | // }); 119 | 120 | const makeServerRequest = new Promise((resolve, reject) => { 121 | // responseFromServer is set to true to represent a successful response from a server 122 | let responseFromServer = true; 123 | 124 | if(responseFromServer) { 125 | resolve("We got the data"); 126 | // write your code here 127 | makeServerRequest.then((result) => { 128 | console.log(result); 129 | }); 130 | } else { 131 | reject("Data not received"); 132 | } 133 | }); 134 | 135 | 136 | /////////////////////////////////////////////////////// 137 | 138 | // ES6: Handle a Rejected Promise with catch 139 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/handle-a-rejected-promise-with-catch 140 | 141 | const makeServerRequest = new Promise((resolve, reject) => { 142 | // responseFromServer is set to false to represent an unsuccessful response from a server 143 | let responseFromServer = false; 144 | 145 | if(responseFromServer) { 146 | resolve("We got the data"); 147 | } else { 148 | reject("Data not received"); 149 | } 150 | }); 151 | 152 | makeServerRequest.then(result => { 153 | console.log(result); 154 | }); 155 | 156 | makeServerRequest.catch((error) => { 157 | console.log(error); 158 | }); -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/freecodeCamp-starting-from-08-31-2020/index.js: -------------------------------------------------------------------------------- 1 | // ES6: Create a Module Script 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-a-module-script 3 | 4 | {/* 5 | 6 | 7 | 8 | 9 | 10 | */} 11 | 12 | ///////////////////////////////////// 13 | 14 | // ES6: Use export to Share a Code Block 15 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-export-to-share-a-code-block 16 | 17 | export const uppercaseString = (string) => { 18 | return string.toUpperCase(); 19 | } 20 | 21 | const lowercaseString = (string) => { 22 | return string.toLowerCase() 23 | } 24 | 25 | export { lowercaseString } 26 | 27 | ///////////////////////////////////// 28 | 29 | // ES6: Reuse JavaScript Code Using import 30 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import 31 | 32 | import { uppercaseString, lowercaseString } from 'string_functions.js'; 33 | // Only change code above this line 34 | 35 | uppercaseString("hello"); 36 | lowercaseString("WORLD!"); 37 | 38 | ///////////////////////////////////// 39 | // ES6: Use * to Import Everything from a File 40 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file 41 | 42 | import * as stringFunctions from "./string_functions.js" 43 | 44 | // Only change code above this line 45 | 46 | stringFunctions.uppercaseString("hello"); 47 | stringFunctions.lowercaseString("WORLD!"); 48 | 49 | ///////////////////////////////////// 50 | 51 | // ES6: Create an Export Fallback with export default 52 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default 53 | 54 | export default function subtract(x, y) { 55 | return x - y; 56 | } 57 | 58 | 59 | https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-a-javascript-promise 60 | // ES6: Import a Default Export 61 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/import-a-default-export 62 | 63 | 64 | 65 | import subtract from "./math_functions.js" 66 | // Only change code above this line 67 | 68 | subtract(7,4); 69 | 70 | ///////////////////////////////////// 71 | 72 | // ES6: Create a JavaScript Promise 73 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-a-javascript-promise 74 | 75 | // promise syntax 76 | //const myPromise = new Promise((resolve, reject) => { 77 | 78 | // }); 79 | 80 | const makeServerRequest = new Promise((resolve, reject) => { 81 | 82 | }); 83 | 84 | 85 | ///////////////////////////////////// 86 | 87 | // ES6: Complete a Promise with resolve and reject 88 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/complete-a-promise-with-resolve-and-reject 89 | 90 | // const myPromise = new Promise((resolve, reject) => { 91 | // if(condition here) { 92 | // resolve("Promise was fulfilled"); 93 | // } else { 94 | // reject("Promise was rejected"); 95 | // } 96 | // }); 97 | 98 | const makeServerRequest = new Promise((resolve, reject) => { 99 | // responseFromServer represents a response from a server 100 | let responseFromServer; 101 | 102 | if(responseFromServer) { 103 | // Change this line 104 | resolve('We got the data'); 105 | } else { 106 | // Change this line 107 | reject('Data not received') 108 | } 109 | }); 110 | 111 | ///////////////////////////////////// 112 | 113 | // ES6: Handle a Fulfilled Promise with then 114 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/handle-a-fulfilled-promise-with-then 115 | 116 | // myPromise.then(result => { 117 | // // do something with the result. 118 | // }); 119 | 120 | const makeServerRequest = new Promise((resolve, reject) => { 121 | // responseFromServer is set to true to represent a successful response from a server 122 | let responseFromServer = true; 123 | 124 | if(responseFromServer) { 125 | resolve("We got the data"); 126 | // write your code here 127 | makeServerRequest.then((result) => { 128 | console.log(result); 129 | }); 130 | } else { 131 | reject("Data not received"); 132 | } 133 | }); 134 | 135 | 136 | /////////////////////////////////////////////////////// 137 | 138 | // ES6: Handle a Rejected Promise with catch 139 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/handle-a-rejected-promise-with-catch 140 | 141 | const makeServerRequest = new Promise((resolve, reject) => { 142 | // responseFromServer is set to false to represent an unsuccessful response from a server 143 | let responseFromServer = false; 144 | 145 | if(responseFromServer) { 146 | resolve("We got the data"); 147 | } else { 148 | reject("Data not received"); 149 | } 150 | }); 151 | 152 | makeServerRequest.then(result => { 153 | console.log(result); 154 | }); 155 | 156 | makeServerRequest.catch((error) => { 157 | console.log(error); 158 | }); -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/4 - Debugging/index.js: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////////////////////// 2 | // Debugging: Catch Mixed Usage of Single and Double Quotes 3 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes 4 | 5 | // // These are correct: 6 | // const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it."; 7 | // const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'"; 8 | // // This is incorrect: 9 | // const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.'; 10 | 11 | // Correct use of same quotes: 12 | // const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.'; 13 | 14 | // Fix the string so it either uses different quotes for the href value, or escape the existing ones. Keep the double quote marks around the entire string. 15 | 16 | // let innerHtml = "

Click here to return home

"; 17 | // console.log(innerHtml); 18 | 19 | //////////////////////////////////////////////////////////////////////////////////////////////// 20 | // Debugging: Catch Use of Assignment Operator Instead of Equality Operator 21 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator 22 | 23 | // let x = 1; 24 | // let y = 2; 25 | // if (x = y) { 26 | // // this code block will run for any value of y (unless y were originally set as a falsy) 27 | // } else { 28 | // // this code block is what should run (but won't) in this example 29 | // } 30 | 31 | // Fix the condition so the program runs the right branch, and the appropriate value is assigned to result. 32 | 33 | // let x = 7; 34 | // let y = 9; 35 | // let result = "to come"; 36 | 37 | // if(x === y) { 38 | // result = "Equal!"; 39 | // } else { 40 | // result = "Not equal!"; 41 | // } 42 | 43 | // console.log(result); 44 | 45 | //////////////////////////////////////////////////////////////////////////////////////////////// 46 | // Debugging: Catch Missing Open and Closing Parenthesis After a Function Call 47 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call 48 | 49 | // function myFunction() { 50 | // return "You rock!"; 51 | // } 52 | // let varOne = myFunction; // set to equal a function 53 | // let varTwo = myFunction(); // set to equal the string "You rock!" 54 | // console.log(varOne()); // You rock! 55 | 56 | // Fix the code so the variable result is set to the value returned from calling the function getNine. 57 | 58 | // function getNine() { 59 | // let x = 6; 60 | // let y = 3; 61 | // return x + y; 62 | // } 63 | 64 | // let result = getNine(); 65 | // console.log(result); 66 | 67 | //////////////////////////////////////////////////////////////////////////////////////////////// 68 | // Debugging: Catch Arguments Passed in the Wrong Order When Calling a Function 69 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-arguments-passed-in-the-wrong-order-when-calling-a-function 70 | 71 | // The function raiseToPower raises a base to an exponent. Unfortunately, it's not called properly - fix the code so the value of power is the expected 8. 72 | 73 | // function raiseToPower(b, e) { 74 | // return Math.pow(b, e); 75 | // } 76 | 77 | // let base = 2; 78 | // let exp = 3; 79 | // let power = raiseToPower(base, exp); 80 | // console.log(power); 81 | 82 | //////////////////////////////////////////////////////////////////////////////////////////////// 83 | // Debugging: Catch Off By One Errors When Using Indexing 84 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing 85 | 86 | // let alphabet = "abcdefghijklmnopqrstuvwxyz"; 87 | // let len = alphabet.length; 88 | // for (let i = 0; i <= len; i++) { 89 | // // loops one too many times at the end 90 | // console.log(alphabet[i]); 91 | // } 92 | // for (let j = 1; j < len; j++) { 93 | // // loops one too few times and misses the first character at index 0 94 | // console.log(alphabet[j]); 95 | // } 96 | // for (let k = 0; k < len; k++) { 97 | // // Goldilocks approves - this is just right 98 | // console.log(alphabet[k]); 99 | // } 100 | 101 | 102 | // Fix the two indexing errors in the following function so all the numbers 1 through 5 are printed to the console. 103 | 104 | function countToFive() { 105 | let firstFive = "12345"; 106 | let len = firstFive.length; 107 | // Only change code below this line 108 | for (let i = 0; i < len; i++) { 109 | // Only change code above this line 110 | console.log(firstFive[i]); 111 | } 112 | } 113 | 114 | countToFive(); 115 | 116 | //////////////////////////////////////////////////////////////////////////////////////////////// 117 | // Debugging: Use Caution When Reinitializing Variables Inside a Loop 118 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop 119 | 120 | // The following function is supposed to create a two-dimensional array with m rows and n columns of zeroes. Unfortunately, it's not producing the expected output because the row variable isn't being reinitialized (set back to an empty array) in the outer loop. Fix the code so it returns a correct 3x2 array of zeroes, which looks like [[0, 0], [0, 0], [0, 0]]. 121 | 122 | function zeroArray(m, n) { 123 | // Creates a 2-D array with m rows and n columns of zeroes 124 | let newArray = []; 125 | 126 | for (let i = 0; i < m; i++) { 127 | // Adds the m-th row into newArray 128 | let row = []; 129 | for (let j = 0; j < n; j++) { 130 | // Pushes n zeroes into the current row to create the columns 131 | row.push(0); 132 | } 133 | // Pushes the current row, which now has n zeroes in it, to the array 134 | newArray.push(row); 135 | } 136 | return newArray; 137 | } 138 | 139 | let matrix = zeroArray(3, 2); 140 | console.log(matrix); 141 | 142 | //////////////////////////////////////////////////////////////////////////////////////////////// 143 | // Debugging: Prevent Infinite Loops with a Valid Terminal Condition 144 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition 145 | 146 | // function loopy() { 147 | // while(true) { 148 | // console.log("Hello, world!"); 149 | // } 150 | // } 151 | 152 | // The myFunc() function contains an infinite loop because the terminal condition i != 4 will never evaluate to false (and break the looping) - i will increment by 2 each pass, and jump right over 4 since i is odd to start. Fix the comparison operator in the terminal condition so the loop only runs for i less than or equal to 4. 153 | 154 | function myFunc() { 155 | for (let i = 1; i <= 4; i += 2) { 156 | console.log("Still going!"); 157 | } 158 | } 159 | 160 | myFunc(); 161 | //////////////////////////////////////////////////////////////////////////////////////////////// 162 | -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/4 - Debugging/index.js: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////////////////////// 2 | // Debugging: Catch Mixed Usage of Single and Double Quotes 3 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes 4 | 5 | // // These are correct: 6 | // const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it."; 7 | // const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'"; 8 | // // This is incorrect: 9 | // const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.'; 10 | 11 | // Correct use of same quotes: 12 | // const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.'; 13 | 14 | // Fix the string so it either uses different quotes for the href value, or escape the existing ones. Keep the double quote marks around the entire string. 15 | 16 | // let innerHtml = "

Click here to return home

"; 17 | // console.log(innerHtml); 18 | 19 | //////////////////////////////////////////////////////////////////////////////////////////////// 20 | // Debugging: Catch Use of Assignment Operator Instead of Equality Operator 21 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator 22 | 23 | // let x = 1; 24 | // let y = 2; 25 | // if (x = y) { 26 | // // this code block will run for any value of y (unless y were originally set as a falsy) 27 | // } else { 28 | // // this code block is what should run (but won't) in this example 29 | // } 30 | 31 | // Fix the condition so the program runs the right branch, and the appropriate value is assigned to result. 32 | 33 | // let x = 7; 34 | // let y = 9; 35 | // let result = "to come"; 36 | 37 | // if(x === y) { 38 | // result = "Equal!"; 39 | // } else { 40 | // result = "Not equal!"; 41 | // } 42 | 43 | // console.log(result); 44 | 45 | //////////////////////////////////////////////////////////////////////////////////////////////// 46 | // Debugging: Catch Missing Open and Closing Parenthesis After a Function Call 47 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call 48 | 49 | // function myFunction() { 50 | // return "You rock!"; 51 | // } 52 | // let varOne = myFunction; // set to equal a function 53 | // let varTwo = myFunction(); // set to equal the string "You rock!" 54 | // console.log(varOne()); // You rock! 55 | 56 | // Fix the code so the variable result is set to the value returned from calling the function getNine. 57 | 58 | // function getNine() { 59 | // let x = 6; 60 | // let y = 3; 61 | // return x + y; 62 | // } 63 | 64 | // let result = getNine(); 65 | // console.log(result); 66 | 67 | //////////////////////////////////////////////////////////////////////////////////////////////// 68 | // Debugging: Catch Arguments Passed in the Wrong Order When Calling a Function 69 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-arguments-passed-in-the-wrong-order-when-calling-a-function 70 | 71 | // The function raiseToPower raises a base to an exponent. Unfortunately, it's not called properly - fix the code so the value of power is the expected 8. 72 | 73 | // function raiseToPower(b, e) { 74 | // return Math.pow(b, e); 75 | // } 76 | 77 | // let base = 2; 78 | // let exp = 3; 79 | // let power = raiseToPower(base, exp); 80 | // console.log(power); 81 | 82 | //////////////////////////////////////////////////////////////////////////////////////////////// 83 | // Debugging: Catch Off By One Errors When Using Indexing 84 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing 85 | 86 | // let alphabet = "abcdefghijklmnopqrstuvwxyz"; 87 | // let len = alphabet.length; 88 | // for (let i = 0; i <= len; i++) { 89 | // // loops one too many times at the end 90 | // console.log(alphabet[i]); 91 | // } 92 | // for (let j = 1; j < len; j++) { 93 | // // loops one too few times and misses the first character at index 0 94 | // console.log(alphabet[j]); 95 | // } 96 | // for (let k = 0; k < len; k++) { 97 | // // Goldilocks approves - this is just right 98 | // console.log(alphabet[k]); 99 | // } 100 | 101 | 102 | // Fix the two indexing errors in the following function so all the numbers 1 through 5 are printed to the console. 103 | 104 | function countToFive() { 105 | let firstFive = "12345"; 106 | let len = firstFive.length; 107 | // Only change code below this line 108 | for (let i = 0; i < len; i++) { 109 | // Only change code above this line 110 | console.log(firstFive[i]); 111 | } 112 | } 113 | 114 | countToFive(); 115 | 116 | //////////////////////////////////////////////////////////////////////////////////////////////// 117 | // Debugging: Use Caution When Reinitializing Variables Inside a Loop 118 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop 119 | 120 | // The following function is supposed to create a two-dimensional array with m rows and n columns of zeroes. Unfortunately, it's not producing the expected output because the row variable isn't being reinitialized (set back to an empty array) in the outer loop. Fix the code so it returns a correct 3x2 array of zeroes, which looks like [[0, 0], [0, 0], [0, 0]]. 121 | 122 | function zeroArray(m, n) { 123 | // Creates a 2-D array with m rows and n columns of zeroes 124 | let newArray = []; 125 | 126 | for (let i = 0; i < m; i++) { 127 | // Adds the m-th row into newArray 128 | let row = []; 129 | for (let j = 0; j < n; j++) { 130 | // Pushes n zeroes into the current row to create the columns 131 | row.push(0); 132 | } 133 | // Pushes the current row, which now has n zeroes in it, to the array 134 | newArray.push(row); 135 | } 136 | return newArray; 137 | } 138 | 139 | let matrix = zeroArray(3, 2); 140 | console.log(matrix); 141 | 142 | //////////////////////////////////////////////////////////////////////////////////////////////// 143 | // Debugging: Prevent Infinite Loops with a Valid Terminal Condition 144 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition 145 | 146 | // function loopy() { 147 | // while(true) { 148 | // console.log("Hello, world!"); 149 | // } 150 | // } 151 | 152 | // The myFunc() function contains an infinite loop because the terminal condition i != 4 will never evaluate to false (and break the looping) - i will increment by 2 each pass, and jump right over 4 since i is odd to start. Fix the comparison operator in the terminal condition so the loop only runs for i less than or equal to 4. 153 | 154 | function myFunc() { 155 | for (let i = 1; i <= 4; i += 2) { 156 | console.log("Still going!"); 157 | } 158 | } 159 | 160 | myFunc(); 161 | //////////////////////////////////////////////////////////////////////////////////////////////// 162 | -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/6 - Basic Algorithm Scripting/index.js: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////////////////////// 2 | // Basic Algorithm Scripting: Convert Celsius to Fahrenheit 3 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting 4 | 5 | // The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times 9/5, plus 32. 6 | 7 | // You are given a variable celsius representing a temperature in Celsius. Use the variable fahrenheit already defined and assign it the Fahrenheit temperature equivalent to the given Celsius temperature. Use the algorithm mentioned above to help convert the Celsius temperature to Fahrenheit. 8 | 9 | // function convertToF(celsius) { 10 | // let fahrenheit = (celsius * 9) / 5 + 32; 11 | // return fahrenheit; 12 | // } 13 | 14 | // convertToF(30); 15 | // console.log(convertToF(30)); 16 | 17 | //////////////////////////////////////////////////////////////////////////////////////////////// 18 | // Basic Algorithm Scripting: Reverse a String 19 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string 20 | // Reverse the provided string. 21 | 22 | // You may need to turn the string into an array before you can reverse it. 23 | 24 | // Your result must be a string. 25 | 26 | // function reverseString(str) { 27 | // let newStr = ''; 28 | // for (let i = str.length-1; i >= 0; i--) { 29 | // newStr += str[i]; 30 | 31 | // } 32 | // return newStr; 33 | // } 34 | 35 | // console.log(reverseString("hello")); 36 | 37 | //////////////////////////////////////////////////////////////////////////////////////////////// 38 | // Basic Algorithm Scripting: Factorialize a Number 39 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number 40 | 41 | // Return the factorial of the provided integer. 42 | // If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n. 43 | // Factorials are often represented with the shorthand notation n! 44 | // For example: 5! = 1 * 2 * 3 * 4 * 5 = 120 45 | // Only integers greater than or equal to zero will be supplied to the function. 46 | 47 | // function factorialize(num) { 48 | // let answer = 1; 49 | // for (let i = num; i >= 1; i--) { 50 | // answer *= i; 51 | // } 52 | // return answer; 53 | // } 54 | 55 | // console.log(factorialize(5)); 56 | 57 | //////////////////////////////////////////////////////////////////////////////////////////////// 58 | // Basic Algorithm Scripting: Find the Longest Word in a String 59 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string 60 | // Return the length of the longest word in the provided sentence. 61 | // Your response should be a number. 62 | 63 | // function findLongestWordLength(str) { 64 | // let longest = 0; 65 | // let strSplit = str.split(' '); 66 | // for (let i = 0; i < strSplit.length; i++) { 67 | // if (strSplit[i].length > longest) longest = strSplit[i].length; 68 | // } 69 | // return longest; 70 | // } 71 | 72 | // console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog")); 73 | 74 | //////////////////////////////////////////////////////////////////////////////////////////////// 75 | // Basic Algorithm Scripting: Return Largest Numbers in Arrays 76 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays 77 | // Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. 78 | 79 | // Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i]. 80 | 81 | // function largestOfFour(arr) { 82 | // let answerArr = []; 83 | // for (let i = 0; i < arr.length; i++) { 84 | // let largest; 85 | // for (let m = 0; m < arr[i].length; m++) { 86 | // if (!largest) largest = arr[i][m]; 87 | // if (arr[i][m] > largest) largest = arr[i][m]; 88 | // } 89 | // answerArr.push(largest) 90 | // } 91 | // return answerArr; 92 | // } 93 | 94 | // console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); 95 | // console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])); 96 | 97 | //////////////////////////////////////////////////////////////////////////////////////////////// 98 | // Basic Algorithm Scripting: Confirm the Ending 99 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending 100 | // Check if a string (first argument, str) ends with the given target string (second argument, target). 101 | 102 | // This challenge can be solved with the .endsWith() method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead. 103 | 104 | // function confirmEnding(str, target) { 105 | // let matchCount = 0; 106 | // for (let i = 0; i < target.length; i++) { 107 | // // start the matching at the first letter of target and the position in str where target should start 108 | // if (target[0 + i] === str[(str.length - target.length) + i]) { 109 | // matchCount++; 110 | // } else { 111 | // return false; 112 | // } 113 | // } 114 | // return matchCount === target.length; 115 | // } 116 | 117 | // console.log(confirmEnding("Bastian", "ian")); 118 | 119 | //////////////////////////////////////////////////////////////////////////////////////////////// 120 | // Basic Algorithm Scripting: Repeat a String Repeat a String 121 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string 122 | // Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number. 123 | 124 | // function repeatStringNumTimes(str, num) { 125 | // if (num <= 0) return ''; 126 | // let answer = ''; 127 | // for (let i = 0; i < num; i++) { 128 | // answer += str; 129 | // } 130 | // return answer; 131 | // } 132 | 133 | // console.log(repeatStringNumTimes("abc", 3)); 134 | 135 | //////////////////////////////////////////////////////////////////////////////////////////////// 136 | // Basic Algorithm Scripting: Truncate a String 137 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string 138 | // Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending. 139 | 140 | // function truncateString(str, num) { 141 | // if (str.length > num) { 142 | // return str.slice(0, num).concat('...'); 143 | // } 144 | // return str; 145 | // } 146 | 147 | // ternary syntax 148 | // const truncateString = (str, num) => str.length > num ? str.slice(0, num).concat('...') : str; 149 | 150 | // console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8)); 151 | 152 | //////////////////////////////////////////////////////////////////////////////////////////////// 153 | // Basic Algorithm Scripting: Finders Keepers 154 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers 155 | // Create a function that looks through an array arr and returns the first element in it that passes a 'truth test'. This means that given an element x, the 'truth test' is passed if func(x) is true. If no element passes the test, return undefined. 156 | 157 | // function findElement(arr, func) { 158 | // let falseCount = 0; 159 | // for (let i = 0; i < arr.length; i++) { 160 | // if (func(arr[i]) === false) { 161 | // falseCount++; 162 | // } else { 163 | // return arr[i]; 164 | // } 165 | // } 166 | // return undefined; 167 | // } 168 | 169 | // console.log(findElement([1, 2, 3, 4], num => num % 2 === 0)); 170 | 171 | //////////////////////////////////////////////////////////////////////////////////////////////// 172 | // Basic Algorithm Scripting: Boo who 173 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who 174 | // Check if a value is classified as a boolean primitive. Return true or false. 175 | 176 | // Boolean primitives are true and false. 177 | 178 | // const booWho = bool => bool === true || bool === false ? true : false; 179 | 180 | // console.log(booWho(null)); 181 | 182 | //////////////////////////////////////////////////////////////////////////////////////////////// 183 | // Basic Algorithm Scripting: Title Case a Sentence 184 | // Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case. 185 | 186 | // For the purpose of this exercise, you should also capitalize connecting words like "the" and "of". 187 | 188 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence 189 | 190 | // const titleCase = str => { 191 | // let result = ''; 192 | // let splitStr = str.toLowerCase().split(' '); 193 | // for (let i = 0; i < splitStr.length; i++) { 194 | // let upper = splitStr[i].slice(0,1).toUpperCase(); 195 | // let theRest = splitStr[i].slice(1); 196 | // let answer = upper.concat(theRest); 197 | // result += answer + ' '; 198 | // } 199 | // return result.slice(0, result.length - 1); 200 | // } 201 | 202 | // console.log(titleCase("I'm a little tea pot")); 203 | // console.log(titleCase("sHoRt AnD sToUt")); 204 | // console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")); 205 | 206 | //////////////////////////////////////////////////////////////////////////////////////////////// 207 | // Basic Algorithm Scripting: Slice and Splice 208 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice 209 | 210 | // You are given two arrays and an index. 211 | 212 | // Copy each element of the first array into the second array, in order. 213 | 214 | // Begin inserting elements at index n of the second array. 215 | 216 | // Return the resulting array. The input arrays should remain the same after the function runs. 217 | 218 | // function frankenSplice(arr1, arr2, n) { 219 | // const myArr1 = [...arr1]; 220 | // const myArr2 = [...arr2]; 221 | // myArr2.splice(n, 0, ...myArr1) 222 | // return myArr2; 223 | // } 224 | 225 | // console.log(frankenSplice([1, 2, 3], [4, 5], 1)); // [4, 1, 2, 3, 5] 226 | // console.log(frankenSplice([1, 2], ["a", "b"], 1)); // ["a", 1, 2, "b"] 227 | // console.log(frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)); // ["head", "shoulders", "claw", "tentacle", "knees", "toes"] 228 | //////////////////////////////////////////////////////////////////////////////////////////////// 229 | // Basic Algorithm Scripting: Falsy Bouncer 230 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer 231 | 232 | // Remove all falsy values from an array. 233 | 234 | // Falsy values in JavaScript are false, null, 0, "", undefined, and NaN. 235 | 236 | // Hint: Try converting each value to a Boolean. 237 | 238 | // function bouncer(arr) { 239 | // const answerArr = []; 240 | // arr.forEach((item) => { 241 | // if (!!item) answerArr.push(item); 242 | // }); 243 | // return answerArr; 244 | // } 245 | 246 | // console.log(bouncer([7, "ate", "", false, 9])); // [7, "ate", 9] 247 | // console.log(bouncer([null, NaN, 1, 2, undefined])); // [1, 2] 248 | 249 | //////////////////////////////////////////////////////////////////////////////////////////////// 250 | // Basic Algorithm Scripting: Where do I Belong 251 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong 252 | // Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number. 253 | 254 | // For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1). 255 | 256 | // Likewise, getIndexToIns([20,3,5], 19) should return 2 because once the array has been sorted it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1). 257 | 258 | // function getIndexToIns(arr, num) { 259 | // if (arr.length === 0) return 0; 260 | // let sorted = arr.sort((a, b) => a - b); 261 | // for (let i = 0; i < sorted.length; i++) { 262 | // if (num === sorted[i]) return i; 263 | // if (num > sorted[i] && num < sorted[i + 1]) return i + 1; 264 | // if (num > sorted[sorted.length - 1]) return sorted.length; 265 | // } 266 | // } 267 | 268 | // console.log(getIndexToIns([3, 10, 5], 3)); // 0 269 | // console.log(getIndexToIns([2, 5, 10], 15)); // 3 270 | // console.log(getIndexToIns([1,2,3,4], 1.5)); // 1 271 | // console.log(getIndexToIns([20,3,5], 19)); // 2 272 | // console.log(getIndexToIns([40, 60], 50)); // 1 273 | // console.log(getIndexToIns([10, 20, 30, 40, 50], 30)); // 2 274 | // console.log(getIndexToIns([], 1)); // 0 275 | 276 | //////////////////////////////////////////////////////////////////////////////////////////////// 277 | // Basic Algorithm Scripting: Mutations 278 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations 279 | 280 | // Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array. 281 | 282 | // For example, ["hello", "Hello"], should return true because all of the letters in the second string are present in the first, ignoring case. 283 | 284 | // The arguments ["hello", "hey"] should return false because the string "hello" does not contain a "y". 285 | 286 | // Lastly, ["Alien", "line"], should return true because all of the letters in "line" are present in "Alien". 287 | 288 | // function mutation(arr) { 289 | // const splitStr1 = arr[0].toLowerCase().split(''); 290 | // const splitStr2 = arr[1].toLowerCase().split(''); 291 | 292 | // for (let i = 0; i < splitStr2.length; i++) { 293 | // if (splitStr1.includes(splitStr2[i]) === false) return false; 294 | // } 295 | // return true; 296 | // } 297 | 298 | // console.log(mutation(["floor", "for"])); // true 299 | // console.log(mutation(["Alien", "line"])); // true 300 | // console.log(mutation(["hello", "Hello"])); // true 301 | // console.log(mutation(["hello", "hey"])); // false 302 | // console.log(mutation(["hello", "neo"])); // false 303 | 304 | //////////////////////////////////////////////////////////////////////////////////////////////// 305 | // Basic Algorithm Scripting: Chunky Monkey 306 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey 307 | // Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array. 308 | 309 | function chunkArrayInGroups(arr, size) { 310 | const answerArr = []; 311 | let newArr = []; 312 | 313 | mainLoop: for (let i = 0; i < arr.length; i++) { 314 | newArr.push(arr[i]); 315 | // once the array hits size, push it to answer 316 | // then reset it to blank 317 | if (newArr.length === size) { 318 | answerArr.push(newArr); 319 | newArr = []; 320 | } 321 | } 322 | // if the final array isn't full it still needs to be push 323 | // but if it's empty because the main array fits the size evenly, don't push it 324 | if (newArr.length !== 0) { 325 | answerArr.push(newArr); 326 | } 327 | return answerArr; 328 | } 329 | 330 | // console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2)); // [["a", "b"], ["c", "d"]] 331 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)); // [[0, 1, 2], [3, 4, 5]]. 332 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)); // [[0, 1], [2, 3], [4, 5]]. 333 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)); // [[0, 1, 2, 3], [4, 5]]. 334 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)); // [[0, 1, 2], [3, 4, 5], [6]]. 335 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)); // [[0, 1, 2, 3], [4, 5, 6, 7], [8]]. 336 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)); // [[0, 1], [2, 3], [4, 5], [6, 7], [8]]. -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/6 - Basic Algorithm Scripting/index.js: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////////////////////// 2 | // Basic Algorithm Scripting: Convert Celsius to Fahrenheit 3 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting 4 | 5 | // The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times 9/5, plus 32. 6 | 7 | // You are given a variable celsius representing a temperature in Celsius. Use the variable fahrenheit already defined and assign it the Fahrenheit temperature equivalent to the given Celsius temperature. Use the algorithm mentioned above to help convert the Celsius temperature to Fahrenheit. 8 | 9 | // function convertToF(celsius) { 10 | // let fahrenheit = (celsius * 9) / 5 + 32; 11 | // return fahrenheit; 12 | // } 13 | 14 | // convertToF(30); 15 | // console.log(convertToF(30)); 16 | 17 | //////////////////////////////////////////////////////////////////////////////////////////////// 18 | // Basic Algorithm Scripting: Reverse a String 19 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string 20 | // Reverse the provided string. 21 | 22 | // You may need to turn the string into an array before you can reverse it. 23 | 24 | // Your result must be a string. 25 | 26 | // function reverseString(str) { 27 | // let newStr = ''; 28 | // for (let i = str.length-1; i >= 0; i--) { 29 | // newStr += str[i]; 30 | 31 | // } 32 | // return newStr; 33 | // } 34 | 35 | // console.log(reverseString("hello")); 36 | 37 | //////////////////////////////////////////////////////////////////////////////////////////////// 38 | // Basic Algorithm Scripting: Factorialize a Number 39 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number 40 | 41 | // Return the factorial of the provided integer. 42 | // If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n. 43 | // Factorials are often represented with the shorthand notation n! 44 | // For example: 5! = 1 * 2 * 3 * 4 * 5 = 120 45 | // Only integers greater than or equal to zero will be supplied to the function. 46 | 47 | // function factorialize(num) { 48 | // let answer = 1; 49 | // for (let i = num; i >= 1; i--) { 50 | // answer *= i; 51 | // } 52 | // return answer; 53 | // } 54 | 55 | // console.log(factorialize(5)); 56 | 57 | //////////////////////////////////////////////////////////////////////////////////////////////// 58 | // Basic Algorithm Scripting: Find the Longest Word in a String 59 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string 60 | // Return the length of the longest word in the provided sentence. 61 | // Your response should be a number. 62 | 63 | // function findLongestWordLength(str) { 64 | // let longest = 0; 65 | // let strSplit = str.split(' '); 66 | // for (let i = 0; i < strSplit.length; i++) { 67 | // if (strSplit[i].length > longest) longest = strSplit[i].length; 68 | // } 69 | // return longest; 70 | // } 71 | 72 | // console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog")); 73 | 74 | //////////////////////////////////////////////////////////////////////////////////////////////// 75 | // Basic Algorithm Scripting: Return Largest Numbers in Arrays 76 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays 77 | // Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. 78 | 79 | // Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i]. 80 | 81 | // function largestOfFour(arr) { 82 | // let answerArr = []; 83 | // for (let i = 0; i < arr.length; i++) { 84 | // let largest; 85 | // for (let m = 0; m < arr[i].length; m++) { 86 | // if (!largest) largest = arr[i][m]; 87 | // if (arr[i][m] > largest) largest = arr[i][m]; 88 | // } 89 | // answerArr.push(largest) 90 | // } 91 | // return answerArr; 92 | // } 93 | 94 | // console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); 95 | // console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])); 96 | 97 | //////////////////////////////////////////////////////////////////////////////////////////////// 98 | // Basic Algorithm Scripting: Confirm the Ending 99 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending 100 | // Check if a string (first argument, str) ends with the given target string (second argument, target). 101 | 102 | // This challenge can be solved with the .endsWith() method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead. 103 | 104 | // function confirmEnding(str, target) { 105 | // let matchCount = 0; 106 | // for (let i = 0; i < target.length; i++) { 107 | // // start the matching at the first letter of target and the position in str where target should start 108 | // if (target[0 + i] === str[(str.length - target.length) + i]) { 109 | // matchCount++; 110 | // } else { 111 | // return false; 112 | // } 113 | // } 114 | // return matchCount === target.length; 115 | // } 116 | 117 | // console.log(confirmEnding("Bastian", "ian")); 118 | 119 | //////////////////////////////////////////////////////////////////////////////////////////////// 120 | // Basic Algorithm Scripting: Repeat a String Repeat a String 121 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string 122 | // Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number. 123 | 124 | // function repeatStringNumTimes(str, num) { 125 | // if (num <= 0) return ''; 126 | // let answer = ''; 127 | // for (let i = 0; i < num; i++) { 128 | // answer += str; 129 | // } 130 | // return answer; 131 | // } 132 | 133 | // console.log(repeatStringNumTimes("abc", 3)); 134 | 135 | //////////////////////////////////////////////////////////////////////////////////////////////// 136 | // Basic Algorithm Scripting: Truncate a String 137 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string 138 | // Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending. 139 | 140 | // function truncateString(str, num) { 141 | // if (str.length > num) { 142 | // return str.slice(0, num).concat('...'); 143 | // } 144 | // return str; 145 | // } 146 | 147 | // ternary syntax 148 | // const truncateString = (str, num) => str.length > num ? str.slice(0, num).concat('...') : str; 149 | 150 | // console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8)); 151 | 152 | //////////////////////////////////////////////////////////////////////////////////////////////// 153 | // Basic Algorithm Scripting: Finders Keepers 154 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers 155 | // Create a function that looks through an array arr and returns the first element in it that passes a 'truth test'. This means that given an element x, the 'truth test' is passed if func(x) is true. If no element passes the test, return undefined. 156 | 157 | // function findElement(arr, func) { 158 | // let falseCount = 0; 159 | // for (let i = 0; i < arr.length; i++) { 160 | // if (func(arr[i]) === false) { 161 | // falseCount++; 162 | // } else { 163 | // return arr[i]; 164 | // } 165 | // } 166 | // return undefined; 167 | // } 168 | 169 | // console.log(findElement([1, 2, 3, 4], num => num % 2 === 0)); 170 | 171 | //////////////////////////////////////////////////////////////////////////////////////////////// 172 | // Basic Algorithm Scripting: Boo who 173 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who 174 | // Check if a value is classified as a boolean primitive. Return true or false. 175 | 176 | // Boolean primitives are true and false. 177 | 178 | // const booWho = bool => bool === true || bool === false ? true : false; 179 | 180 | // console.log(booWho(null)); 181 | 182 | //////////////////////////////////////////////////////////////////////////////////////////////// 183 | // Basic Algorithm Scripting: Title Case a Sentence 184 | // Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case. 185 | 186 | // For the purpose of this exercise, you should also capitalize connecting words like "the" and "of". 187 | 188 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence 189 | 190 | // const titleCase = str => { 191 | // let result = ''; 192 | // let splitStr = str.toLowerCase().split(' '); 193 | // for (let i = 0; i < splitStr.length; i++) { 194 | // let upper = splitStr[i].slice(0,1).toUpperCase(); 195 | // let theRest = splitStr[i].slice(1); 196 | // let answer = upper.concat(theRest); 197 | // result += answer + ' '; 198 | // } 199 | // return result.slice(0, result.length - 1); 200 | // } 201 | 202 | // console.log(titleCase("I'm a little tea pot")); 203 | // console.log(titleCase("sHoRt AnD sToUt")); 204 | // console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")); 205 | 206 | //////////////////////////////////////////////////////////////////////////////////////////////// 207 | // Basic Algorithm Scripting: Slice and Splice 208 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice 209 | 210 | // You are given two arrays and an index. 211 | 212 | // Copy each element of the first array into the second array, in order. 213 | 214 | // Begin inserting elements at index n of the second array. 215 | 216 | // Return the resulting array. The input arrays should remain the same after the function runs. 217 | 218 | // function frankenSplice(arr1, arr2, n) { 219 | // const myArr1 = [...arr1]; 220 | // const myArr2 = [...arr2]; 221 | // myArr2.splice(n, 0, ...myArr1) 222 | // return myArr2; 223 | // } 224 | 225 | // console.log(frankenSplice([1, 2, 3], [4, 5], 1)); // [4, 1, 2, 3, 5] 226 | // console.log(frankenSplice([1, 2], ["a", "b"], 1)); // ["a", 1, 2, "b"] 227 | // console.log(frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)); // ["head", "shoulders", "claw", "tentacle", "knees", "toes"] 228 | //////////////////////////////////////////////////////////////////////////////////////////////// 229 | // Basic Algorithm Scripting: Falsy Bouncer 230 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer 231 | 232 | // Remove all falsy values from an array. 233 | 234 | // Falsy values in JavaScript are false, null, 0, "", undefined, and NaN. 235 | 236 | // Hint: Try converting each value to a Boolean. 237 | 238 | // function bouncer(arr) { 239 | // const answerArr = []; 240 | // arr.forEach((item) => { 241 | // if (!!item) answerArr.push(item); 242 | // }); 243 | // return answerArr; 244 | // } 245 | 246 | // console.log(bouncer([7, "ate", "", false, 9])); // [7, "ate", 9] 247 | // console.log(bouncer([null, NaN, 1, 2, undefined])); // [1, 2] 248 | 249 | //////////////////////////////////////////////////////////////////////////////////////////////// 250 | // Basic Algorithm Scripting: Where do I Belong 251 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong 252 | // Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number. 253 | 254 | // For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1). 255 | 256 | // Likewise, getIndexToIns([20,3,5], 19) should return 2 because once the array has been sorted it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1). 257 | 258 | // function getIndexToIns(arr, num) { 259 | // if (arr.length === 0) return 0; 260 | // let sorted = arr.sort((a, b) => a - b); 261 | // for (let i = 0; i < sorted.length; i++) { 262 | // if (num === sorted[i]) return i; 263 | // if (num > sorted[i] && num < sorted[i + 1]) return i + 1; 264 | // if (num > sorted[sorted.length - 1]) return sorted.length; 265 | // } 266 | // } 267 | 268 | // console.log(getIndexToIns([3, 10, 5], 3)); // 0 269 | // console.log(getIndexToIns([2, 5, 10], 15)); // 3 270 | // console.log(getIndexToIns([1,2,3,4], 1.5)); // 1 271 | // console.log(getIndexToIns([20,3,5], 19)); // 2 272 | // console.log(getIndexToIns([40, 60], 50)); // 1 273 | // console.log(getIndexToIns([10, 20, 30, 40, 50], 30)); // 2 274 | // console.log(getIndexToIns([], 1)); // 0 275 | 276 | //////////////////////////////////////////////////////////////////////////////////////////////// 277 | // Basic Algorithm Scripting: Mutations 278 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations 279 | 280 | // Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array. 281 | 282 | // For example, ["hello", "Hello"], should return true because all of the letters in the second string are present in the first, ignoring case. 283 | 284 | // The arguments ["hello", "hey"] should return false because the string "hello" does not contain a "y". 285 | 286 | // Lastly, ["Alien", "line"], should return true because all of the letters in "line" are present in "Alien". 287 | 288 | // function mutation(arr) { 289 | // const splitStr1 = arr[0].toLowerCase().split(''); 290 | // const splitStr2 = arr[1].toLowerCase().split(''); 291 | 292 | // for (let i = 0; i < splitStr2.length; i++) { 293 | // if (splitStr1.includes(splitStr2[i]) === false) return false; 294 | // } 295 | // return true; 296 | // } 297 | 298 | // console.log(mutation(["floor", "for"])); // true 299 | // console.log(mutation(["Alien", "line"])); // true 300 | // console.log(mutation(["hello", "Hello"])); // true 301 | // console.log(mutation(["hello", "hey"])); // false 302 | // console.log(mutation(["hello", "neo"])); // false 303 | 304 | //////////////////////////////////////////////////////////////////////////////////////////////// 305 | // Basic Algorithm Scripting: Chunky Monkey 306 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey 307 | // Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array. 308 | 309 | function chunkArrayInGroups(arr, size) { 310 | const answerArr = []; 311 | let newArr = []; 312 | 313 | mainLoop: for (let i = 0; i < arr.length; i++) { 314 | newArr.push(arr[i]); 315 | // once the array hits size, push it to answer 316 | // then reset it to blank 317 | if (newArr.length === size) { 318 | answerArr.push(newArr); 319 | newArr = []; 320 | } 321 | } 322 | // if the final array isn't full it still needs to be push 323 | // but if it's empty because the main array fits the size evenly, don't push it 324 | if (newArr.length !== 0) { 325 | answerArr.push(newArr); 326 | } 327 | return answerArr; 328 | } 329 | 330 | // console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2)); // [["a", "b"], ["c", "d"]] 331 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)); // [[0, 1, 2], [3, 4, 5]]. 332 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)); // [[0, 1], [2, 3], [4, 5]]. 333 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)); // [[0, 1, 2, 3], [4, 5]]. 334 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)); // [[0, 1, 2], [3, 4, 5], [6]]. 335 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)); // [[0, 1, 2, 3], [4, 5, 6, 7], [8]]. 336 | // console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)); // [[0, 1], [2, 3], [4, 5], [6, 7], [8]]. -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/5 - Basic-Data-Structures/index.js: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////////////////////// 2 | // Basic Data Structures: Use an Array to Store a Collection of Data 3 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data 4 | 5 | // We have defined a variable called yourArray. Complete the statement by assigning an array of at least 5 elements in length to the yourArray variable. Your array should contain at least one string, one number, and one boolean. 6 | 7 | // let yourArray; // Change this line 8 | // let yourArray = [1, '2', 3, 4, true]; 9 | 10 | //////////////////////////////////////////////////////////////////////////////////////////////// 11 | // Basic Data Structures: Access an Array's Contents Using Bracket Notation 12 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/access-an-arrays-contents-using-bracket-notation 13 | 14 | // In order to complete this challenge, set the 2nd position (index 1) of myArray to anything you want, besides "b". 15 | 16 | // let myArray = ["a", "b", "c", "d"]; 17 | // // Only change code below this line 18 | // myArray[1] = 5; 19 | // // Only change code above this line 20 | // console.log(myArray); 21 | //////////////////////////////////////////////////////////////////////////////////////////////// 22 | // Basic Data Structures: Add Items to an Array with push() and unshift() 23 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/add-items-to-an-array-with-push-and-unshift 24 | 25 | // We have defined a function, mixedNumbers, which we are passing an array as an argument. Modify the function by using push() and unshift() to add 'I', 2, 'three' to the beginning of the array and 7, 'VIII', 9 to the end so that the returned array contains representations of the numbers 1-9 in order. 26 | 27 | // function mixedNumbers(arr) { 28 | // // Only change code below this line 29 | // arr.unshift('I', 2, 'three'); 30 | // arr.push(7, 'VIII', 9); 31 | // // Only change code above this line 32 | // return arr; 33 | // } 34 | 35 | // console.log(mixedNumbers(['IV', 5, 'six'])); 36 | 37 | //////////////////////////////////////////////////////////////////////////////////////////////// 38 | // Basic Data Structures: Remove Items from an Array with pop() and shift() 39 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift 40 | // We have defined a function, popShift, which takes an array as an argument and returns a new array. Modify the function, using pop() and shift(), to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values. 41 | 42 | // function popShift(arr) { 43 | // let popped = arr.pop(); // Change this line 44 | // let shifted = arr.shift(); // Change this line 45 | // return [shifted, popped]; 46 | // } 47 | 48 | // console.log(popShift(['challenge', 'is', 'not', 'complete'])); 49 | 50 | //////////////////////////////////////////////////////////////////////////////////////////////// 51 | // Basic Data Structures: Remove Items Using splice() 52 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice 53 | // We've initialized an array arr. Use splice() to remove elements from arr, so that it only contains elements that sum to the value of 10. 54 | 55 | // const arr = [2, 4, 5, 1, 7, 5, 2, 1]; 56 | // // Only change code below this line 57 | // arr.splice(1, 4); 58 | // // Only change code above this line 59 | // console.log(arr); 60 | 61 | //////////////////////////////////////////////////////////////////////////////////////////////// 62 | // Basic Data Structures: Add Items Using splice() 63 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice 64 | 65 | // const numbers = [10, 11, 12, 12, 15]; 66 | // const startIndex = 3; 67 | // const amountToDelete = 1; 68 | 69 | // numbers.splice(startIndex, amountToDelete, 13, 14); 70 | // // the second entry of 12 is removed, and we add 13 and 14 at the same index 71 | // console.log(numbers); 72 | // // returns [ 10, 11, 12, 13, 14, 15 ] 73 | 74 | // We have defined a function, htmlColorNames, which takes an array of HTML colors as an argument. Modify the function using splice() to remove the first two elements of the array and add 'DarkSalmon' and 'BlanchedAlmond' in their respective places. 75 | 76 | // function htmlColorNames(arr) { 77 | // // Only change code below this line 78 | // arr.splice(0, 2, 'DarkSalmon', 'BlanchedAlmond') 79 | // // Only change code above this line 80 | // return arr; 81 | // } 82 | 83 | // console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurquoise', 'FireBrick'])); 84 | 85 | //////////////////////////////////////////////////////////////////////////////////////////////// 86 | // Basic Data Structures: Copy Array Items Using slice() 87 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice 88 | 89 | // let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear']; 90 | 91 | // let todaysWeather = weatherConditions.slice(1, 3); 92 | // todaysWeather equals ['snow', 'sleet']; 93 | // weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear'] 94 | 95 | // We have defined a function, forecast, that takes an array as an argument. Modify the function using slice() to extract information from the argument array and return a new array that contains the elements 'warm' and 'sunny'. 96 | 97 | // function forecast(arr) { 98 | // // Only change code below this line 99 | // let newArr = arr.slice(2, 4); 100 | // return newArr; 101 | // } 102 | 103 | // // Only change code above this line 104 | // console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms'])); 105 | 106 | //////////////////////////////////////////////////////////////////////////////////////////////// 107 | // Basic Data Structures: Copy an Array with the Spread Operator 108 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator 109 | 110 | // We have defined a function, copyMachine which takes arr (an array) and num (a number) as arguments. The function is supposed to return a new array made up of num copies of arr. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!). 111 | 112 | // function copyMachine(arr, num) { 113 | // let newArr = []; 114 | // while (num >= 1) { 115 | // // Only change code below this line 116 | // newArr.push([...arr]); 117 | // // Only change code above this line 118 | // num--; 119 | // } 120 | // return newArr; 121 | // } 122 | 123 | // console.log(copyMachine([true, false, true], 2)); 124 | 125 | //////////////////////////////////////////////////////////////////////////////////////////////// 126 | // Basic Data Structures: Combine Arrays with the Spread Operator 127 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator 128 | 129 | // We have defined a function spreadOut that returns the variable sentence. Modify the function using the spread operator so that it returns the array ['learning', 'to', 'code', 'is', 'fun']. 130 | 131 | // function spreadOut() { 132 | // let fragment = ['to', 'code']; 133 | // let sentence = ['learning', ...fragment, 'is', 'fun']; // Change this line 134 | // return sentence; 135 | // } 136 | 137 | // console.log(spreadOut()); 138 | 139 | //////////////////////////////////////////////////////////////////////////////////////////////// 140 | // Basic Data Structures: Check For The Presence of an Element With indexOf() 141 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof 142 | // indexOf() can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, quickCheck, that takes an array and an element as arguments. Modify the function using indexOf() so that it returns true if the passed element exists on the array, and false if it does not. 143 | 144 | // let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears']; 145 | 146 | // fruits.indexOf('dates'); // returns -1 147 | // fruits.indexOf('oranges'); // returns 2 148 | // fruits.indexOf('pears'); // returns 1, the first index at which the element exists 149 | 150 | // function quickCheck(arr, elem) { 151 | // // Only change code below this line 152 | // // freeCodeCamp didn't like this syntax 153 | // // return arr.indexOf(elem) > 0 ? true : false; 154 | // if (arr.indexOf(elem) === -1) { 155 | // return false; 156 | // } else { 157 | // return true; 158 | // } 159 | // Only change code above this line 160 | // } 161 | 162 | // console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms')); 163 | // console.log(quickCheck(['squash', 'onions', 'shallots'], 'onions')); 164 | 165 | //////////////////////////////////////////////////////////////////////////////////////////////// 166 | // Basic Data Structures: Iterate Through All an Array's Items Using For Loops 167 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops 168 | 169 | // We have defined a function, filteredArray, which takes arr, a nested array, and elem as arguments, and returns a new array. elem represents an element that may or may not be present on one or more of the arrays nested within arr. Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed. 170 | 171 | // function filteredArray(arr, elem) { 172 | // let newArr = []; 173 | // // Only change code below this line 174 | // for (let i = 0; i < arr.length; i++) { 175 | // if (arr[i].indexOf(elem) === -1) { 176 | // newArr.push(arr[i]); 177 | // } 178 | // } 179 | // // Only change code above this line 180 | // return newArr; 181 | // } 182 | 183 | // console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)); 184 | 185 | //////////////////////////////////////////////////////////////////////////////////////////////// 186 | // Basic Data Structures: Create complex multi-dimensional arrays 187 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays 188 | // We have defined a variable, myNestedArray, set equal to an array. Modify myNestedArray, using any combination of strings, numbers, and booleans for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string 'deep', on the fourth level, include the string 'deeper', and on the fifth level, include the string 'deepest'. 189 | 190 | // let myNestedArray = [ 191 | // [ 192 | // [ 193 | // 'deep', 194 | // ], 195 | // [ 196 | // [ 197 | // 'deeper', 198 | // ], 199 | // [ 200 | // [ 201 | // 'deepest', 202 | // ] 203 | // ], 204 | // ], 205 | // ], 206 | // ] 207 | 208 | //////////////////////////////////////////////////////////////////////////////////////////////// 209 | // Basic Data Structures: Add Key-Value Pairs to JavaScript Objects 210 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects 211 | // A foods object has been created with three entries. Using the syntax of your choice, add three more entries to it: bananas with a value of 13, grapes with a value of 35, and strawberries with a value of 27. 212 | 213 | // let foods = { 214 | // apples: 25, 215 | // oranges: 32, 216 | // plums: 28 217 | // }; 218 | 219 | // Only change code below this line 220 | // let food1 = 'strawberries'; 221 | // foods.bananas = 13; 222 | // foods.grapes = 35; 223 | // foods[food1] = 27; 224 | // // Only change code above this line 225 | 226 | // console.log(foods); 227 | 228 | //////////////////////////////////////////////////////////////////////////////////////////////// 229 | // Basic Data Structures: Modify an Object Nested Within an Object 230 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/modify-an-object-nested-within-an-object 231 | // Here we've defined an object userActivity, which includes another object nested within it. Set the value of the online key to 45. 232 | 233 | // let userActivity = { 234 | // id: 23894201352, 235 | // date: 'January 1, 2017', 236 | // data: { 237 | // totalUsers: 51, 238 | // online: 42 239 | // } 240 | // }; 241 | 242 | // // Only change code below this line 243 | // userActivity.data.online = 45; 244 | // // Only change code above this line 245 | 246 | // console.log(userActivity); 247 | 248 | //////////////////////////////////////////////////////////////////////////////////////////////// 249 | // Basic Data Structures: Access Property Names with Bracket Notation 250 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/access-property-names-with-bracket-notation 251 | 252 | // We've defined a function, checkInventory, which receives a scanned item as an argument. Return the current value of the scannedItem key in the foods object. You can assume that only valid keys will be provided as an argument to checkInventory. 253 | 254 | // let foods = { 255 | // apples: 25, 256 | // oranges: 32, 257 | // plums: 28, 258 | // bananas: 13, 259 | // grapes: 35, 260 | // strawberries: 27 261 | // }; 262 | 263 | // function checkInventory(scannedItem) { 264 | // // Only change code below this line 265 | // return foods[scannedItem]; 266 | // // Only change code above this line 267 | // } 268 | 269 | // console.log(checkInventory("apples")); 270 | 271 | //////////////////////////////////////////////////////////////////////////////////////////////// 272 | // Basic Data Structures: Use the delete Keyword to Remove Object Properties 273 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/use-the-delete-keyword-to-remove-object-properties 274 | 275 | // Use the delete keyword to remove the oranges, plums, and strawberries keys from the foods object. 276 | 277 | // let foods = { 278 | // apples: 25, 279 | // oranges: 32, 280 | // plums: 28, 281 | // bananas: 13, 282 | // grapes: 35, 283 | // strawberries: 27 284 | // }; 285 | 286 | // Only change code below this line 287 | // delete foods.oranges; 288 | // delete foods.plums; 289 | // delete foods.strawberries; 290 | // Only change code above this line 291 | 292 | // console.log(foods); 293 | 294 | //////////////////////////////////////////////////////////////////////////////////////////////// 295 | // Basic Data Structures: Check if an Object has a Property 296 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property 297 | // We've created an object, users, with some users in it and a function isEveryoneHere, which we pass the users object to as an argument. Finish writing this function so that it returns true only if the users object contains all four names, Alan, Jeff, Sarah, and Ryan, as keys, and false otherwise. 298 | 299 | // let users = { 300 | // Alan: { 301 | // age: 27, 302 | // online: true 303 | // }, 304 | // Jeff: { 305 | // age: 32, 306 | // online: true 307 | // }, 308 | // Sarah: { 309 | // age: 48, 310 | // online: true 311 | // }, 312 | // Ryan: { 313 | // age: 19, 314 | // online: true 315 | // } 316 | // }; 317 | 318 | // function isEveryoneHere(obj) { 319 | // // Only change code below this line 320 | // // returns true only if the users object contains all four names, Alan, Jeff, Sarah, and Ryan, as keys, and false otherwise. 321 | // if (obj['Alan'] && obj['Jeff'] && obj['Sarah'] && obj['Ryan']) return true; 322 | // return false; 323 | // // Only change code above this line 324 | // } 325 | 326 | // console.log(isEveryoneHere(users)); 327 | 328 | //////////////////////////////////////////////////////////////////////////////////////////////// 329 | // Basic Data Structures: Iterate Through the Keys of an Object with a for...in Statement 330 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for---in-statement 331 | 332 | // We've defined a function countOnline which accepts one argument (a users object). Use a for...in statement within this function to loop through the users object passed into the function and return the number of users whose online property is set to true. An example of a users object which could be passed to countOnline is shown below. Each user will have an online property with either a true or false value. 333 | 334 | // const myUsers = { 335 | // Alan: { 336 | // online: false 337 | // }, 338 | // Jeff: { 339 | // online: true 340 | // }, 341 | // Sarah: { 342 | // online: false 343 | // } 344 | // } 345 | 346 | // function countOnline(usersObj) { 347 | // // Only change code below this line 348 | // let numOnline = 0; 349 | // for (const property in usersObj) { 350 | // if (usersObj[property].online === true) numOnline++; 351 | // } 352 | // return numOnline; 353 | // // Only change code above this line 354 | // } 355 | 356 | // console.log(countOnline(myUsers)); 357 | 358 | //////////////////////////////////////////////////////////////////////////////////////////////// 359 | // Basic Data Structures: Generate an Array of All Object Keys with Object.keys() 360 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/generate-an-array-of-all-object-keys-with-object-keys 361 | // Finish writing the getArrayOfUsers function so that it returns an array containing all the properties in the object it receives as an argument. 362 | 363 | // let users = { 364 | // Alan: { 365 | // age: 27, 366 | // online: false 367 | // }, 368 | // Jeff: { 369 | // age: 32, 370 | // online: true 371 | // }, 372 | // Sarah: { 373 | // age: 48, 374 | // online: false 375 | // }, 376 | // Ryan: { 377 | // age: 19, 378 | // online: true 379 | // } 380 | // }; 381 | 382 | // function getArrayOfUsers(obj) { 383 | // Only change code below this line 384 | // return Object.keys(users); 385 | // Only change code above this line 386 | // } 387 | 388 | // console.log(getArrayOfUsers(users)); 389 | 390 | //////////////////////////////////////////////////////////////////////////////////////////////// 391 | // Basic Data Structures: Modify an Array Stored in an Object 392 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object 393 | // Take a look at the object we've provided in the code editor. The user object contains three keys. The data key contains five keys, one of which contains an array of friends. From this, you can see how flexible objects are as data structures. We've started writing a function addFriend. Finish writing it so that it takes a user object and adds the name of the friend argument to the array stored in user.data.friends and returns that array. 394 | 395 | let user = { 396 | name: 'Kenneth', 397 | age: 28, 398 | data: { 399 | username: 'kennethCodesAllDay', 400 | joinDate: 'March 26, 2016', 401 | organization: 'freeCodeCamp', 402 | friends: [ 403 | 'Sam', 404 | 'Kira', 405 | 'Tomo' 406 | ], 407 | location: { 408 | city: 'San Francisco', 409 | state: 'CA', 410 | country: 'USA' 411 | } 412 | } 413 | }; 414 | 415 | function addFriend(userObj, friend) { 416 | // Only change code below this line 417 | userObj['data']['friends'].push(friend); 418 | return userObj['data']['friends']; 419 | // Only change code above this line 420 | } 421 | 422 | console.log(addFriend(user, 'Pete')); 423 | -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/5 - Basic-Data-Structures/index.js: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////////////////////// 2 | // Basic Data Structures: Use an Array to Store a Collection of Data 3 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data 4 | 5 | // We have defined a variable called yourArray. Complete the statement by assigning an array of at least 5 elements in length to the yourArray variable. Your array should contain at least one string, one number, and one boolean. 6 | 7 | // let yourArray; // Change this line 8 | // let yourArray = [1, '2', 3, 4, true]; 9 | 10 | //////////////////////////////////////////////////////////////////////////////////////////////// 11 | // Basic Data Structures: Access an Array's Contents Using Bracket Notation 12 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/access-an-arrays-contents-using-bracket-notation 13 | 14 | // In order to complete this challenge, set the 2nd position (index 1) of myArray to anything you want, besides "b". 15 | 16 | // let myArray = ["a", "b", "c", "d"]; 17 | // // Only change code below this line 18 | // myArray[1] = 5; 19 | // // Only change code above this line 20 | // console.log(myArray); 21 | //////////////////////////////////////////////////////////////////////////////////////////////// 22 | // Basic Data Structures: Add Items to an Array with push() and unshift() 23 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/add-items-to-an-array-with-push-and-unshift 24 | 25 | // We have defined a function, mixedNumbers, which we are passing an array as an argument. Modify the function by using push() and unshift() to add 'I', 2, 'three' to the beginning of the array and 7, 'VIII', 9 to the end so that the returned array contains representations of the numbers 1-9 in order. 26 | 27 | // function mixedNumbers(arr) { 28 | // // Only change code below this line 29 | // arr.unshift('I', 2, 'three'); 30 | // arr.push(7, 'VIII', 9); 31 | // // Only change code above this line 32 | // return arr; 33 | // } 34 | 35 | // console.log(mixedNumbers(['IV', 5, 'six'])); 36 | 37 | //////////////////////////////////////////////////////////////////////////////////////////////// 38 | // Basic Data Structures: Remove Items from an Array with pop() and shift() 39 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift 40 | // We have defined a function, popShift, which takes an array as an argument and returns a new array. Modify the function, using pop() and shift(), to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values. 41 | 42 | // function popShift(arr) { 43 | // let popped = arr.pop(); // Change this line 44 | // let shifted = arr.shift(); // Change this line 45 | // return [shifted, popped]; 46 | // } 47 | 48 | // console.log(popShift(['challenge', 'is', 'not', 'complete'])); 49 | 50 | //////////////////////////////////////////////////////////////////////////////////////////////// 51 | // Basic Data Structures: Remove Items Using splice() 52 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice 53 | // We've initialized an array arr. Use splice() to remove elements from arr, so that it only contains elements that sum to the value of 10. 54 | 55 | // const arr = [2, 4, 5, 1, 7, 5, 2, 1]; 56 | // // Only change code below this line 57 | // arr.splice(1, 4); 58 | // // Only change code above this line 59 | // console.log(arr); 60 | 61 | //////////////////////////////////////////////////////////////////////////////////////////////// 62 | // Basic Data Structures: Add Items Using splice() 63 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice 64 | 65 | // const numbers = [10, 11, 12, 12, 15]; 66 | // const startIndex = 3; 67 | // const amountToDelete = 1; 68 | 69 | // numbers.splice(startIndex, amountToDelete, 13, 14); 70 | // // the second entry of 12 is removed, and we add 13 and 14 at the same index 71 | // console.log(numbers); 72 | // // returns [ 10, 11, 12, 13, 14, 15 ] 73 | 74 | // We have defined a function, htmlColorNames, which takes an array of HTML colors as an argument. Modify the function using splice() to remove the first two elements of the array and add 'DarkSalmon' and 'BlanchedAlmond' in their respective places. 75 | 76 | // function htmlColorNames(arr) { 77 | // // Only change code below this line 78 | // arr.splice(0, 2, 'DarkSalmon', 'BlanchedAlmond') 79 | // // Only change code above this line 80 | // return arr; 81 | // } 82 | 83 | // console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurquoise', 'FireBrick'])); 84 | 85 | //////////////////////////////////////////////////////////////////////////////////////////////// 86 | // Basic Data Structures: Copy Array Items Using slice() 87 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice 88 | 89 | // let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear']; 90 | 91 | // let todaysWeather = weatherConditions.slice(1, 3); 92 | // todaysWeather equals ['snow', 'sleet']; 93 | // weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear'] 94 | 95 | // We have defined a function, forecast, that takes an array as an argument. Modify the function using slice() to extract information from the argument array and return a new array that contains the elements 'warm' and 'sunny'. 96 | 97 | // function forecast(arr) { 98 | // // Only change code below this line 99 | // let newArr = arr.slice(2, 4); 100 | // return newArr; 101 | // } 102 | 103 | // // Only change code above this line 104 | // console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms'])); 105 | 106 | //////////////////////////////////////////////////////////////////////////////////////////////// 107 | // Basic Data Structures: Copy an Array with the Spread Operator 108 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator 109 | 110 | // We have defined a function, copyMachine which takes arr (an array) and num (a number) as arguments. The function is supposed to return a new array made up of num copies of arr. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!). 111 | 112 | // function copyMachine(arr, num) { 113 | // let newArr = []; 114 | // while (num >= 1) { 115 | // // Only change code below this line 116 | // newArr.push([...arr]); 117 | // // Only change code above this line 118 | // num--; 119 | // } 120 | // return newArr; 121 | // } 122 | 123 | // console.log(copyMachine([true, false, true], 2)); 124 | 125 | //////////////////////////////////////////////////////////////////////////////////////////////// 126 | // Basic Data Structures: Combine Arrays with the Spread Operator 127 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator 128 | 129 | // We have defined a function spreadOut that returns the variable sentence. Modify the function using the spread operator so that it returns the array ['learning', 'to', 'code', 'is', 'fun']. 130 | 131 | // function spreadOut() { 132 | // let fragment = ['to', 'code']; 133 | // let sentence = ['learning', ...fragment, 'is', 'fun']; // Change this line 134 | // return sentence; 135 | // } 136 | 137 | // console.log(spreadOut()); 138 | 139 | //////////////////////////////////////////////////////////////////////////////////////////////// 140 | // Basic Data Structures: Check For The Presence of an Element With indexOf() 141 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof 142 | // indexOf() can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, quickCheck, that takes an array and an element as arguments. Modify the function using indexOf() so that it returns true if the passed element exists on the array, and false if it does not. 143 | 144 | // let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears']; 145 | 146 | // fruits.indexOf('dates'); // returns -1 147 | // fruits.indexOf('oranges'); // returns 2 148 | // fruits.indexOf('pears'); // returns 1, the first index at which the element exists 149 | 150 | // function quickCheck(arr, elem) { 151 | // // Only change code below this line 152 | // // freeCodeCamp didn't like this syntax 153 | // // return arr.indexOf(elem) > 0 ? true : false; 154 | // if (arr.indexOf(elem) === -1) { 155 | // return false; 156 | // } else { 157 | // return true; 158 | // } 159 | // Only change code above this line 160 | // } 161 | 162 | // console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms')); 163 | // console.log(quickCheck(['squash', 'onions', 'shallots'], 'onions')); 164 | 165 | //////////////////////////////////////////////////////////////////////////////////////////////// 166 | // Basic Data Structures: Iterate Through All an Array's Items Using For Loops 167 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops 168 | 169 | // We have defined a function, filteredArray, which takes arr, a nested array, and elem as arguments, and returns a new array. elem represents an element that may or may not be present on one or more of the arrays nested within arr. Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed. 170 | 171 | // function filteredArray(arr, elem) { 172 | // let newArr = []; 173 | // // Only change code below this line 174 | // for (let i = 0; i < arr.length; i++) { 175 | // if (arr[i].indexOf(elem) === -1) { 176 | // newArr.push(arr[i]); 177 | // } 178 | // } 179 | // // Only change code above this line 180 | // return newArr; 181 | // } 182 | 183 | // console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)); 184 | 185 | //////////////////////////////////////////////////////////////////////////////////////////////// 186 | // Basic Data Structures: Create complex multi-dimensional arrays 187 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays 188 | // We have defined a variable, myNestedArray, set equal to an array. Modify myNestedArray, using any combination of strings, numbers, and booleans for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string 'deep', on the fourth level, include the string 'deeper', and on the fifth level, include the string 'deepest'. 189 | 190 | // let myNestedArray = [ 191 | // [ 192 | // [ 193 | // 'deep', 194 | // ], 195 | // [ 196 | // [ 197 | // 'deeper', 198 | // ], 199 | // [ 200 | // [ 201 | // 'deepest', 202 | // ] 203 | // ], 204 | // ], 205 | // ], 206 | // ] 207 | 208 | //////////////////////////////////////////////////////////////////////////////////////////////// 209 | // Basic Data Structures: Add Key-Value Pairs to JavaScript Objects 210 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects 211 | // A foods object has been created with three entries. Using the syntax of your choice, add three more entries to it: bananas with a value of 13, grapes with a value of 35, and strawberries with a value of 27. 212 | 213 | // let foods = { 214 | // apples: 25, 215 | // oranges: 32, 216 | // plums: 28 217 | // }; 218 | 219 | // Only change code below this line 220 | // let food1 = 'strawberries'; 221 | // foods.bananas = 13; 222 | // foods.grapes = 35; 223 | // foods[food1] = 27; 224 | // // Only change code above this line 225 | 226 | // console.log(foods); 227 | 228 | //////////////////////////////////////////////////////////////////////////////////////////////// 229 | // Basic Data Structures: Modify an Object Nested Within an Object 230 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/modify-an-object-nested-within-an-object 231 | // Here we've defined an object userActivity, which includes another object nested within it. Set the value of the online key to 45. 232 | 233 | // let userActivity = { 234 | // id: 23894201352, 235 | // date: 'January 1, 2017', 236 | // data: { 237 | // totalUsers: 51, 238 | // online: 42 239 | // } 240 | // }; 241 | 242 | // // Only change code below this line 243 | // userActivity.data.online = 45; 244 | // // Only change code above this line 245 | 246 | // console.log(userActivity); 247 | 248 | //////////////////////////////////////////////////////////////////////////////////////////////// 249 | // Basic Data Structures: Access Property Names with Bracket Notation 250 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/access-property-names-with-bracket-notation 251 | 252 | // We've defined a function, checkInventory, which receives a scanned item as an argument. Return the current value of the scannedItem key in the foods object. You can assume that only valid keys will be provided as an argument to checkInventory. 253 | 254 | // let foods = { 255 | // apples: 25, 256 | // oranges: 32, 257 | // plums: 28, 258 | // bananas: 13, 259 | // grapes: 35, 260 | // strawberries: 27 261 | // }; 262 | 263 | // function checkInventory(scannedItem) { 264 | // // Only change code below this line 265 | // return foods[scannedItem]; 266 | // // Only change code above this line 267 | // } 268 | 269 | // console.log(checkInventory("apples")); 270 | 271 | //////////////////////////////////////////////////////////////////////////////////////////////// 272 | // Basic Data Structures: Use the delete Keyword to Remove Object Properties 273 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/use-the-delete-keyword-to-remove-object-properties 274 | 275 | // Use the delete keyword to remove the oranges, plums, and strawberries keys from the foods object. 276 | 277 | // let foods = { 278 | // apples: 25, 279 | // oranges: 32, 280 | // plums: 28, 281 | // bananas: 13, 282 | // grapes: 35, 283 | // strawberries: 27 284 | // }; 285 | 286 | // Only change code below this line 287 | // delete foods.oranges; 288 | // delete foods.plums; 289 | // delete foods.strawberries; 290 | // Only change code above this line 291 | 292 | // console.log(foods); 293 | 294 | //////////////////////////////////////////////////////////////////////////////////////////////// 295 | // Basic Data Structures: Check if an Object has a Property 296 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property 297 | // We've created an object, users, with some users in it and a function isEveryoneHere, which we pass the users object to as an argument. Finish writing this function so that it returns true only if the users object contains all four names, Alan, Jeff, Sarah, and Ryan, as keys, and false otherwise. 298 | 299 | // let users = { 300 | // Alan: { 301 | // age: 27, 302 | // online: true 303 | // }, 304 | // Jeff: { 305 | // age: 32, 306 | // online: true 307 | // }, 308 | // Sarah: { 309 | // age: 48, 310 | // online: true 311 | // }, 312 | // Ryan: { 313 | // age: 19, 314 | // online: true 315 | // } 316 | // }; 317 | 318 | // function isEveryoneHere(obj) { 319 | // // Only change code below this line 320 | // // returns true only if the users object contains all four names, Alan, Jeff, Sarah, and Ryan, as keys, and false otherwise. 321 | // if (obj['Alan'] && obj['Jeff'] && obj['Sarah'] && obj['Ryan']) return true; 322 | // return false; 323 | // // Only change code above this line 324 | // } 325 | 326 | // console.log(isEveryoneHere(users)); 327 | 328 | //////////////////////////////////////////////////////////////////////////////////////////////// 329 | // Basic Data Structures: Iterate Through the Keys of an Object with a for...in Statement 330 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for---in-statement 331 | 332 | // We've defined a function countOnline which accepts one argument (a users object). Use a for...in statement within this function to loop through the users object passed into the function and return the number of users whose online property is set to true. An example of a users object which could be passed to countOnline is shown below. Each user will have an online property with either a true or false value. 333 | 334 | // const myUsers = { 335 | // Alan: { 336 | // online: false 337 | // }, 338 | // Jeff: { 339 | // online: true 340 | // }, 341 | // Sarah: { 342 | // online: false 343 | // } 344 | // } 345 | 346 | // function countOnline(usersObj) { 347 | // // Only change code below this line 348 | // let numOnline = 0; 349 | // for (const property in usersObj) { 350 | // if (usersObj[property].online === true) numOnline++; 351 | // } 352 | // return numOnline; 353 | // // Only change code above this line 354 | // } 355 | 356 | // console.log(countOnline(myUsers)); 357 | 358 | //////////////////////////////////////////////////////////////////////////////////////////////// 359 | // Basic Data Structures: Generate an Array of All Object Keys with Object.keys() 360 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/generate-an-array-of-all-object-keys-with-object-keys 361 | // Finish writing the getArrayOfUsers function so that it returns an array containing all the properties in the object it receives as an argument. 362 | 363 | // let users = { 364 | // Alan: { 365 | // age: 27, 366 | // online: false 367 | // }, 368 | // Jeff: { 369 | // age: 32, 370 | // online: true 371 | // }, 372 | // Sarah: { 373 | // age: 48, 374 | // online: false 375 | // }, 376 | // Ryan: { 377 | // age: 19, 378 | // online: true 379 | // } 380 | // }; 381 | 382 | // function getArrayOfUsers(obj) { 383 | // Only change code below this line 384 | // return Object.keys(users); 385 | // Only change code above this line 386 | // } 387 | 388 | // console.log(getArrayOfUsers(users)); 389 | 390 | //////////////////////////////////////////////////////////////////////////////////////////////// 391 | // Basic Data Structures: Modify an Array Stored in an Object 392 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object 393 | // Take a look at the object we've provided in the code editor. The user object contains three keys. The data key contains five keys, one of which contains an array of friends. From this, you can see how flexible objects are as data structures. We've started writing a function addFriend. Finish writing it so that it takes a user object and adds the name of the friend argument to the array stored in user.data.friends and returns that array. 394 | 395 | let user = { 396 | name: 'Kenneth', 397 | age: 28, 398 | data: { 399 | username: 'kennethCodesAllDay', 400 | joinDate: 'March 26, 2016', 401 | organization: 'freeCodeCamp', 402 | friends: [ 403 | 'Sam', 404 | 'Kira', 405 | 'Tomo' 406 | ], 407 | location: { 408 | city: 'San Francisco', 409 | state: 'CA', 410 | country: 'USA' 411 | } 412 | } 413 | }; 414 | 415 | function addFriend(userObj, friend) { 416 | // Only change code below this line 417 | userObj['data']['friends'].push(friend); 418 | return userObj['data']['friends']; 419 | // Only change code above this line 420 | } 421 | 422 | console.log(addFriend(user, 'Pete')); 423 | -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/7 - Object Oriented Programming/index.js: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////// 2 | // Object Oriented Programming: Create a Basic JavaScript Object 3 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/create-a-basic-javascript-object 4 | // Create a dog object with name and numLegs properties, and set them to a string and a number, respectively. 5 | 6 | // let dog = { 7 | // name: 'dog', 8 | // numLegs: 4, 9 | // }; 10 | 11 | /////////////////////////////////////////////////////////////////////////////// 12 | // Use Dot Notation to Access the Properties of an Object 13 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-dot-notation-to-access-the-properties-of-an-object 14 | 15 | // Print both properties of the dog object to your console. 16 | 17 | // let dog = { 18 | // name: "Spot", 19 | // numLegs: 4 20 | // }; 21 | // Only change code below this line 22 | // console.log(dog.name); 23 | // console.log(dog.numLegs) 24 | 25 | /////////////////////////////////////////////////////////////////////////////// 26 | // Create a Method on an Object 27 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object 28 | // Using the dog object, give it a method called sayLegs. The method should return the sentence "This dog has 4 legs." 29 | 30 | // let dog = { 31 | // name: "Spot", 32 | // numLegs: 4, 33 | // sayLegs: function () {return "This dog has 4 legs."} 34 | // }; 35 | 36 | // console.log(dog.sayLegs()); 37 | 38 | /////////////////////////////////////////////////////////////////////////////// 39 | // Make Code More Reusable with the this Keyword 40 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword 41 | // Modify the dog.sayLegs method to remove any references to dog. Use the duck example for guidance. 42 | 43 | // let dog = { 44 | // name: "Spot", 45 | // numLegs: 4, 46 | // sayLegs: function() {return "This dog has " + this.numLegs + " legs.";} 47 | // }; 48 | 49 | // console.log(dog.sayLegs()); 50 | 51 | /////////////////////////////////////////////////////////////////////////////// 52 | // Define a Constructor Function 53 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function 54 | // Create a constructor, Dog, with properties name, color, and numLegs that are set to a string, a string, and a number, respectively. 55 | 56 | // function Dog() { 57 | // this.name = 'Dog', 58 | // this.color = 'Brown', 59 | // this.numLegs = 4 60 | // }; 61 | 62 | // const dog1 = new Dog('dig', 'beige', 3); 63 | // console.log(dog1) 64 | 65 | /////////////////////////////////////////////////////////////////////////////// 66 | // Use a Constructor to Create Objects 67 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-a-constructor-to-create-objects 68 | // Use the Dog constructor from the last lesson to create a new instance of Dog, assigning it to a variable hound. 69 | 70 | // function Dog() { 71 | // this.name = "Rupert"; 72 | // this.color = "brown"; 73 | // this.numLegs = 4; 74 | // } 75 | // // Only change code below this line 76 | // const hound = new Dog(); 77 | // console.log(hound) 78 | 79 | /////////////////////////////////////////////////////////////////////////////// 80 | // Extend Constructors to Receive Arguments 81 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/extend-constructors-to-receive-arguments 82 | // Create another Dog constructor. This time, set it up to take the parameters name and color, and have the property numLegs fixed at 4. Then create a new Dog saved in a variable terrier. Pass it two strings as arguments for the name and color properties. 83 | 84 | // function Dog(name, color) { 85 | // this.name = name; 86 | // this.color = color; 87 | // this.numLegs = 4; 88 | // } 89 | 90 | // const terrier = new Dog('dog2', 'blue'); 91 | // console.log(terrier); 92 | 93 | /////////////////////////////////////////////////////////////////////////////// 94 | // Verify an Object's Constructor with instanceof 95 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/verify-an-objects-constructor-with-instanceof 96 | // Anytime a constructor function creates a new object, that object is said to be an instance of its constructor. JavaScript gives a convenient way to verify this with the instanceof operator. instanceof allows you to compare an object to a constructor, returning true or false based on whether or not that object was created with the constructor. Here's an example: 97 | 98 | // let Bird = function(name, color) { 99 | // this.name = name; 100 | // this.color = color; 101 | // this.numLegs = 2; 102 | // } 103 | 104 | // let crow = new Bird("Alexis", "black"); 105 | 106 | // console.log(crow instanceof Bird); // => true 107 | 108 | // Create a new instance of the House constructor, calling it myHouse and passing a number of bedrooms. Then, use instanceof to verify that it is an instance of House. 109 | 110 | // function House(numBedrooms) { 111 | // this.numBedrooms = numBedrooms; 112 | // } 113 | 114 | // Only change code below this line 115 | // const myHouse = new House(3); 116 | // console.log(myHouse instanceof House); 117 | 118 | /////////////////////////////////////////////////////////////////////////////// 119 | // Understand Own Properties 120 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties 121 | // Add the own properties of canary to the array ownProps. 122 | 123 | // function Bird(name) { 124 | // this.name = name; 125 | // this.numLegs = 2; 126 | // } 127 | 128 | // let canary = new Bird("Tweety"); 129 | // let ownProps = []; 130 | // // Only change code below this line 131 | // for (const property in canary) { 132 | // if (canary.hasOwnProperty(property)) ownProps.push(property); 133 | // } 134 | 135 | // console.log(ownProps); 136 | 137 | /////////////////////////////////////////////////////////////////////////////// 138 | // Use Prototype Properties to Reduce Duplicate Code 139 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code 140 | // Add a numLegs property to the prototype of Dog 141 | 142 | // function Dog(name) { 143 | // this.name = name; 144 | // } 145 | 146 | // Dog.prototype.numLegs = 4; 147 | 148 | // Only change code above this line 149 | // let beagle = new Dog("Snoopy"); 150 | // console.log(beagle); 151 | // console.log(beagle.hasOwnProperty('numLegs')); 152 | // console.log(beagle.hasOwnProperty('name')); 153 | 154 | /////////////////////////////////////////////////////////////////////////////// 155 | // Iterate Over All Properties 156 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties 157 | // Add all of the own properties of beagle to the array ownProps. Add all of the prototype properties of Dog to the array prototypeProps. 158 | 159 | // function Dog(name) { 160 | // this.name = name; 161 | // } 162 | 163 | // Dog.prototype.numLegs = 4; 164 | 165 | // let beagle = new Dog("Snoopy"); 166 | 167 | // let ownProps = []; 168 | // let prototypeProps = []; 169 | 170 | // Only change code below this line 171 | // for (const property in beagle) { 172 | // beagle.hasOwnProperty(property) ? ownProps.push(property) : prototypeProps.push(property); 173 | // } 174 | // console.log(ownProps); 175 | // console.log(prototypeProps); 176 | 177 | /////////////////////////////////////////////////////////////////////////////// 178 | // Understand the Constructor Property 179 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-constructor-property 180 | // Write a joinDogFraternity function that takes a candidate parameter and, using the constructor property, return true if the candidate is a Dog, otherwise return false. 181 | 182 | // function Dog(name) { 183 | // this.name = name; 184 | // } 185 | 186 | // Only change code below this line 187 | // const joinDogFraternity = candidate => candidate.constructor === Dog ? true : false; 188 | 189 | // let beagle = new Dog("Snoopy"); 190 | // console.log(joinDogFraternity(beagle)); 191 | 192 | /////////////////////////////////////////////////////////////////////////////// 193 | // Change the Prototype to a New Object 194 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object 195 | // Add the property numLegs and the two methods eat() and describe() to the prototype of Dog by setting the prototype to a new object. 196 | 197 | // function Dog(name) { 198 | // this.name = name; 199 | // } 200 | 201 | // Dog.prototype = { 202 | // // Only change code below this line 203 | // numLegs: 4, 204 | 205 | // eat: function() { 206 | // console.log('eat'); 207 | // return 'eat'; 208 | // }, 209 | 210 | // describe: function() { 211 | // console.log('My name is ' + this.name); 212 | // return 'My name is ' + this.name; 213 | // } 214 | // }; 215 | 216 | // let beagle = new Dog("Snoopy"); 217 | // console.log(beagle.eat()); 218 | // console.log(beagle.describe()); 219 | 220 | /////////////////////////////////////////////////////////////////////////////// 221 | // Remember to Set the Constructor Property when Changing the Prototype 222 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype 223 | // Define the constructor property on the Dog prototype. 224 | 225 | // function Dog(name) { 226 | // this.name = name; 227 | // } 228 | 229 | // // Only change code below this line 230 | // Dog.prototype = { 231 | // constructor: Dog, 232 | // numLegs: 4, 233 | // eat: function() { 234 | // console.log("nom nom nom"); 235 | // }, 236 | // describe: function() { 237 | // console.log("My name is " + this.name); 238 | // } 239 | // }; 240 | 241 | /////////////////////////////////////////////////////////////////////////////// 242 | // Understand Where an Object’s Prototype Comes From 243 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-where-an-objects-prototype-comes-from 244 | 245 | // function Bird(name) { 246 | // this.name = name; 247 | // } 248 | 249 | // let duck = new Bird("Donald"); 250 | 251 | // Bird.prototype.isPrototypeOf(duck); returns true 252 | 253 | // Use isPrototypeOf to check the prototype of beagle. 254 | 255 | // function Dog(name) { 256 | // this.name = name; 257 | // } 258 | 259 | // let beagle = new Dog("Snoopy"); 260 | 261 | // // Only change code below this line 262 | // console.log(Dog.prototype.isPrototypeOf(beagle)); 263 | 264 | /////////////////////////////////////////////////////////////////////////////// 265 | // Understand the Prototype Chain 266 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-prototype-chain 267 | // Modify the code to show the correct prototype chain. 268 | 269 | // function Dog(name) { 270 | // this.name = name; 271 | // } 272 | 273 | // let beagle = new Dog("Snoopy"); 274 | 275 | // console.log(Dog.prototype.isPrototypeOf(beagle)); // yields true 276 | 277 | // // Fix the code below so that it evaluates to true 278 | // console.log(Object.prototype.isPrototypeOf(Dog.prototype)); 279 | 280 | /////////////////////////////////////////////////////////////////////////////// 281 | // Use Inheritance So You Don't Repeat Yourself 282 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself 283 | // The eat method is repeated in both Cat and Bear. Edit the code in the spirit of DRY by moving the eat method to the Animal supertype. 284 | 285 | // function Cat(name) { 286 | // this.name = name; 287 | // } 288 | 289 | // Cat.prototype = { 290 | // constructor: Cat, 291 | // }; 292 | 293 | // function Bear(name) { 294 | // this.name = name; 295 | // } 296 | 297 | // Bear.prototype = { 298 | // constructor: Bear, 299 | // }; 300 | 301 | // function Animal() { } 302 | 303 | // Animal.prototype = { 304 | // constructor: Animal, 305 | // eat: function() { 306 | // console.log("nom nom nom"); 307 | // } 308 | // }; 309 | 310 | /////////////////////////////////////////////////////////////////////////////// 311 | // Inherit Behaviors from a Supertype 312 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/inherit-behaviors-from-a-supertype 313 | // Use Object.create to make two instances of Animal named duck and beagle. 314 | 315 | // function Animal() { } 316 | 317 | // Animal.prototype = { 318 | // constructor: Animal, 319 | // eat: function() { 320 | // console.log("nom nom nom"); 321 | // } 322 | // }; 323 | 324 | // Only change code below this line 325 | 326 | // let duck = Object.create(Animal.prototype); // Change this line 327 | // let beagle = Object.create(Animal.prototype); // Change this line 328 | // console.log(duck.eat()); 329 | // console.log(beagle); 330 | 331 | /////////////////////////////////////////////////////////////////////////////// 332 | // Set the Child's Prototype to an Instance of the Parent 333 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent 334 | // Modify the code so that instances of Dog inherit from Animal. 335 | 336 | // function Animal() { } 337 | 338 | // Animal.prototype = { 339 | // constructor: Animal, 340 | // eat: function() { 341 | // console.log("nom nom nom"); 342 | // } 343 | // }; 344 | 345 | // function Dog() { } 346 | 347 | // // Only change code below this line 348 | // Dog.prototype = Object.create(Animal.prototype); 349 | 350 | // let beagle = new Dog(); 351 | // console.log(beagle.eat()); 352 | 353 | /////////////////////////////////////////////////////////////////////////////// 354 | // Reset an Inherited Constructor Property 355 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/reset-an-inherited-constructor-property 356 | // Fix the code so duck.constructor and beagle.constructor return their respective constructors. 357 | 358 | // function Animal() { } 359 | // function Bird() { } 360 | // function Dog() { } 361 | 362 | // Bird.prototype = Object.create(Animal.prototype); 363 | // Dog.prototype = Object.create(Animal.prototype); 364 | 365 | // // Only change code below this line 366 | // Bird.prototype.constructor = Bird; 367 | // Dog.prototype.constructor = Dog; 368 | 369 | // let duck = new Bird(); 370 | // let beagle = new Dog(); 371 | // console.log(duck); 372 | // console.log(beagle); 373 | 374 | /////////////////////////////////////////////////////////////////////////////// 375 | // Add Methods After Inheritance 376 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance 377 | // Add all necessary code so the Dog object inherits from Animal and the Dog's prototype constructor is set to Dog. Then add a bark() method to the Dog object so that beagle can both eat() and bark(). The bark() method should print "Woof!" to the console. 378 | 379 | // function Animal() { } 380 | // Animal.prototype.eat = function() { console.log("nom nom nom"); }; 381 | 382 | // function Dog() { } 383 | 384 | // // Only change code below this line 385 | // Dog.prototype = Object.create(Animal.prototype); 386 | // Dog.prototype.constructor = Dog; 387 | 388 | // Dog.prototype.bark = function () { 389 | // console.log('Woof!'); 390 | // }; 391 | 392 | 393 | 394 | // // Only change code above this line 395 | 396 | // let beagle = new Dog(); 397 | // console.log(beagle.bark()); 398 | 399 | /////////////////////////////////////////////////////////////////////////////// 400 | // Override Inherited Methods 401 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods 402 | // Override the fly() method for Penguin so that it returns "Alas, this is a flightless bird." 403 | 404 | // function Bird() { } 405 | 406 | // Bird.prototype.fly = function() { return "I am flying!"; }; 407 | 408 | // function Penguin() { } 409 | // Penguin.prototype = Object.create(Bird.prototype); 410 | // Penguin.prototype.constructor = Penguin; 411 | 412 | // // Only change code below this line 413 | 414 | // Penguin.prototype.fly = function() { return "Alas, this is a flightless bird."; }; 415 | 416 | // // Only change code above this line 417 | 418 | // let penguin = new Penguin(); 419 | // console.log(penguin.fly()); 420 | 421 | /////////////////////////////////////////////////////////////////////////////// 422 | // Use a Mixin to Add Common Behavior Between Unrelated Objects 423 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-a-mixin-to-add-common-behavior-between-unrelated-objects 424 | 425 | // The flyMixin takes any object and gives it the fly method. 426 | 427 | // let bird = { 428 | // name: "Donald", 429 | // numLegs: 2 430 | // }; 431 | 432 | // let plane = { 433 | // model: "777", 434 | // numPassengers: 524 435 | // }; 436 | 437 | // flyMixin(bird); 438 | // flyMixin(plane); 439 | 440 | // Create a mixin named glideMixin that defines a method named glide. Then use the glideMixin to give both bird and boat the ability to glide. 441 | 442 | // let bird = { 443 | // name: "Donald", 444 | // numLegs: 2 445 | // }; 446 | 447 | // let boat = { 448 | // name: "Warrior", 449 | // type: "race-boat" 450 | // }; 451 | 452 | // // Only change code below this line 453 | // const glideMixin = obj => { 454 | // obj.glide = function () { 455 | // console.log('I can glide!'); 456 | // return 'I can glide!' 457 | // } 458 | // } 459 | 460 | // glideMixin(boat); 461 | // glideMixin(bird); 462 | // console.log(bird.glide()); 463 | // console.log(boat.glide()); 464 | 465 | /////////////////////////////////////////////////////////////////////////////// 466 | // Use Closure to Protect Properties Within an Object from Being Modified Externally 467 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-closure-to-protect-properties-within-an-object-from-being-modified-externally 468 | 469 | function Bird() { 470 | let hatchedEgg = 10; // private variable 471 | 472 | /* publicly available method that a bird object can use */ 473 | this.getHatchedEggCount = function() { 474 | return hatchedEgg; 475 | }; 476 | } 477 | let ducky = new Bird(); 478 | ducky.getHatchedEggCount(); // returns 10 479 | 480 | // Change how weight is declared in the Bird function so it is a private variable. Then, create a method getWeight that returns the value of weight 15. 481 | 482 | function Bird() { 483 | // private variable 484 | let weight = 15; 485 | 486 | // privileged public access 487 | this.getWeight = function () { 488 | console.log(weight); 489 | return weight; 490 | } 491 | } 492 | 493 | // const bird2 = new Bird(); 494 | // console.log(bird2); 495 | // console.log(bird2.getWeight()); 496 | 497 | /////////////////////////////////////////////////////////////////////////////// 498 | // Understand the Immediately Invoked Function Expression (IIFE) 499 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife 500 | 501 | (function () { 502 | console.log("Chirp, chirp!"); 503 | })(); // this is an anonymous function expression that executes right away 504 | // Outputs "Chirp, chirp!" immediately 505 | 506 | // Rewrite the function makeNest and remove its call so instead it's an anonymous immediately invoked function expression (IIFE). 507 | 508 | function makeNest() { 509 | console.log("A cozy nest is ready"); 510 | return "A cozy nest is ready"; 511 | } 512 | 513 | console.log(makeNest()); 514 | 515 | (function () { 516 | console.log("A cozy nest is ready"); 517 | return "A cozy nest is ready"; 518 | })(); 519 | 520 | /////////////////////////////////////////////////////////////////////////////// 521 | // Use an IIFE to Create a Module 522 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module 523 | 524 | let motionModule = (function () { 525 | return { 526 | glideMixin: function(obj) { 527 | obj.glide = function() { 528 | console.log("Gliding on the water"); 529 | }; 530 | }, 531 | flyMixin: function(obj) { 532 | obj.fly = function() { 533 | console.log("Flying, wooosh!"); 534 | }; 535 | } 536 | } 537 | })(); // The two parentheses cause the function to be immediately invoked 538 | 539 | // motionModule.glideMixin(duck); 540 | // duck.glide(); 541 | 542 | // Create a module named funModule to wrap the two mixins isCuteMixin and singMixin. funModule should return an object. 543 | 544 | // let singMixin = function(obj) { 545 | // obj.sing = function() { 546 | // console.log("Singing to an awesome tune"); 547 | // }; 548 | // }; 549 | 550 | const funModule = (function () { 551 | return { 552 | isCuteMixin: function (obj) { 553 | obj.isCute = function () { 554 | return true; 555 | } 556 | }, 557 | 558 | singMixin: function (obj) { 559 | obj.sing = function () { 560 | console.log("Singing to an awesome tune"); 561 | return "Singing to an awesome tune"; 562 | 563 | } 564 | } 565 | } 566 | })(); 567 | 568 | const duck = {}; 569 | 570 | // funModule.singMixin(duck); 571 | // console.log(duck.sing()); -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/7 - Object Oriented Programming/index.js: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////// 2 | // Object Oriented Programming: Create a Basic JavaScript Object 3 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/create-a-basic-javascript-object 4 | // Create a dog object with name and numLegs properties, and set them to a string and a number, respectively. 5 | 6 | // let dog = { 7 | // name: 'dog', 8 | // numLegs: 4, 9 | // }; 10 | 11 | /////////////////////////////////////////////////////////////////////////////// 12 | // Use Dot Notation to Access the Properties of an Object 13 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-dot-notation-to-access-the-properties-of-an-object 14 | 15 | // Print both properties of the dog object to your console. 16 | 17 | // let dog = { 18 | // name: "Spot", 19 | // numLegs: 4 20 | // }; 21 | // Only change code below this line 22 | // console.log(dog.name); 23 | // console.log(dog.numLegs) 24 | 25 | /////////////////////////////////////////////////////////////////////////////// 26 | // Create a Method on an Object 27 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object 28 | // Using the dog object, give it a method called sayLegs. The method should return the sentence "This dog has 4 legs." 29 | 30 | // let dog = { 31 | // name: "Spot", 32 | // numLegs: 4, 33 | // sayLegs: function () {return "This dog has 4 legs."} 34 | // }; 35 | 36 | // console.log(dog.sayLegs()); 37 | 38 | /////////////////////////////////////////////////////////////////////////////// 39 | // Make Code More Reusable with the this Keyword 40 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword 41 | // Modify the dog.sayLegs method to remove any references to dog. Use the duck example for guidance. 42 | 43 | // let dog = { 44 | // name: "Spot", 45 | // numLegs: 4, 46 | // sayLegs: function() {return "This dog has " + this.numLegs + " legs.";} 47 | // }; 48 | 49 | // console.log(dog.sayLegs()); 50 | 51 | /////////////////////////////////////////////////////////////////////////////// 52 | // Define a Constructor Function 53 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function 54 | // Create a constructor, Dog, with properties name, color, and numLegs that are set to a string, a string, and a number, respectively. 55 | 56 | // function Dog() { 57 | // this.name = 'Dog', 58 | // this.color = 'Brown', 59 | // this.numLegs = 4 60 | // }; 61 | 62 | // const dog1 = new Dog('dig', 'beige', 3); 63 | // console.log(dog1) 64 | 65 | /////////////////////////////////////////////////////////////////////////////// 66 | // Use a Constructor to Create Objects 67 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-a-constructor-to-create-objects 68 | // Use the Dog constructor from the last lesson to create a new instance of Dog, assigning it to a variable hound. 69 | 70 | // function Dog() { 71 | // this.name = "Rupert"; 72 | // this.color = "brown"; 73 | // this.numLegs = 4; 74 | // } 75 | // // Only change code below this line 76 | // const hound = new Dog(); 77 | // console.log(hound) 78 | 79 | /////////////////////////////////////////////////////////////////////////////// 80 | // Extend Constructors to Receive Arguments 81 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/extend-constructors-to-receive-arguments 82 | // Create another Dog constructor. This time, set it up to take the parameters name and color, and have the property numLegs fixed at 4. Then create a new Dog saved in a variable terrier. Pass it two strings as arguments for the name and color properties. 83 | 84 | // function Dog(name, color) { 85 | // this.name = name; 86 | // this.color = color; 87 | // this.numLegs = 4; 88 | // } 89 | 90 | // const terrier = new Dog('dog2', 'blue'); 91 | // console.log(terrier); 92 | 93 | /////////////////////////////////////////////////////////////////////////////// 94 | // Verify an Object's Constructor with instanceof 95 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/verify-an-objects-constructor-with-instanceof 96 | // Anytime a constructor function creates a new object, that object is said to be an instance of its constructor. JavaScript gives a convenient way to verify this with the instanceof operator. instanceof allows you to compare an object to a constructor, returning true or false based on whether or not that object was created with the constructor. Here's an example: 97 | 98 | // let Bird = function(name, color) { 99 | // this.name = name; 100 | // this.color = color; 101 | // this.numLegs = 2; 102 | // } 103 | 104 | // let crow = new Bird("Alexis", "black"); 105 | 106 | // console.log(crow instanceof Bird); // => true 107 | 108 | // Create a new instance of the House constructor, calling it myHouse and passing a number of bedrooms. Then, use instanceof to verify that it is an instance of House. 109 | 110 | // function House(numBedrooms) { 111 | // this.numBedrooms = numBedrooms; 112 | // } 113 | 114 | // Only change code below this line 115 | // const myHouse = new House(3); 116 | // console.log(myHouse instanceof House); 117 | 118 | /////////////////////////////////////////////////////////////////////////////// 119 | // Understand Own Properties 120 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties 121 | // Add the own properties of canary to the array ownProps. 122 | 123 | // function Bird(name) { 124 | // this.name = name; 125 | // this.numLegs = 2; 126 | // } 127 | 128 | // let canary = new Bird("Tweety"); 129 | // let ownProps = []; 130 | // // Only change code below this line 131 | // for (const property in canary) { 132 | // if (canary.hasOwnProperty(property)) ownProps.push(property); 133 | // } 134 | 135 | // console.log(ownProps); 136 | 137 | /////////////////////////////////////////////////////////////////////////////// 138 | // Use Prototype Properties to Reduce Duplicate Code 139 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code 140 | // Add a numLegs property to the prototype of Dog 141 | 142 | // function Dog(name) { 143 | // this.name = name; 144 | // } 145 | 146 | // Dog.prototype.numLegs = 4; 147 | 148 | // Only change code above this line 149 | // let beagle = new Dog("Snoopy"); 150 | // console.log(beagle); 151 | // console.log(beagle.hasOwnProperty('numLegs')); 152 | // console.log(beagle.hasOwnProperty('name')); 153 | 154 | /////////////////////////////////////////////////////////////////////////////// 155 | // Iterate Over All Properties 156 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties 157 | // Add all of the own properties of beagle to the array ownProps. Add all of the prototype properties of Dog to the array prototypeProps. 158 | 159 | // function Dog(name) { 160 | // this.name = name; 161 | // } 162 | 163 | // Dog.prototype.numLegs = 4; 164 | 165 | // let beagle = new Dog("Snoopy"); 166 | 167 | // let ownProps = []; 168 | // let prototypeProps = []; 169 | 170 | // Only change code below this line 171 | // for (const property in beagle) { 172 | // beagle.hasOwnProperty(property) ? ownProps.push(property) : prototypeProps.push(property); 173 | // } 174 | // console.log(ownProps); 175 | // console.log(prototypeProps); 176 | 177 | /////////////////////////////////////////////////////////////////////////////// 178 | // Understand the Constructor Property 179 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-constructor-property 180 | // Write a joinDogFraternity function that takes a candidate parameter and, using the constructor property, return true if the candidate is a Dog, otherwise return false. 181 | 182 | // function Dog(name) { 183 | // this.name = name; 184 | // } 185 | 186 | // Only change code below this line 187 | // const joinDogFraternity = candidate => candidate.constructor === Dog ? true : false; 188 | 189 | // let beagle = new Dog("Snoopy"); 190 | // console.log(joinDogFraternity(beagle)); 191 | 192 | /////////////////////////////////////////////////////////////////////////////// 193 | // Change the Prototype to a New Object 194 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object 195 | // Add the property numLegs and the two methods eat() and describe() to the prototype of Dog by setting the prototype to a new object. 196 | 197 | // function Dog(name) { 198 | // this.name = name; 199 | // } 200 | 201 | // Dog.prototype = { 202 | // // Only change code below this line 203 | // numLegs: 4, 204 | 205 | // eat: function() { 206 | // console.log('eat'); 207 | // return 'eat'; 208 | // }, 209 | 210 | // describe: function() { 211 | // console.log('My name is ' + this.name); 212 | // return 'My name is ' + this.name; 213 | // } 214 | // }; 215 | 216 | // let beagle = new Dog("Snoopy"); 217 | // console.log(beagle.eat()); 218 | // console.log(beagle.describe()); 219 | 220 | /////////////////////////////////////////////////////////////////////////////// 221 | // Remember to Set the Constructor Property when Changing the Prototype 222 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype 223 | // Define the constructor property on the Dog prototype. 224 | 225 | // function Dog(name) { 226 | // this.name = name; 227 | // } 228 | 229 | // // Only change code below this line 230 | // Dog.prototype = { 231 | // constructor: Dog, 232 | // numLegs: 4, 233 | // eat: function() { 234 | // console.log("nom nom nom"); 235 | // }, 236 | // describe: function() { 237 | // console.log("My name is " + this.name); 238 | // } 239 | // }; 240 | 241 | /////////////////////////////////////////////////////////////////////////////// 242 | // Understand Where an Object’s Prototype Comes From 243 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-where-an-objects-prototype-comes-from 244 | 245 | // function Bird(name) { 246 | // this.name = name; 247 | // } 248 | 249 | // let duck = new Bird("Donald"); 250 | 251 | // Bird.prototype.isPrototypeOf(duck); returns true 252 | 253 | // Use isPrototypeOf to check the prototype of beagle. 254 | 255 | // function Dog(name) { 256 | // this.name = name; 257 | // } 258 | 259 | // let beagle = new Dog("Snoopy"); 260 | 261 | // // Only change code below this line 262 | // console.log(Dog.prototype.isPrototypeOf(beagle)); 263 | 264 | /////////////////////////////////////////////////////////////////////////////// 265 | // Understand the Prototype Chain 266 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-prototype-chain 267 | // Modify the code to show the correct prototype chain. 268 | 269 | // function Dog(name) { 270 | // this.name = name; 271 | // } 272 | 273 | // let beagle = new Dog("Snoopy"); 274 | 275 | // console.log(Dog.prototype.isPrototypeOf(beagle)); // yields true 276 | 277 | // // Fix the code below so that it evaluates to true 278 | // console.log(Object.prototype.isPrototypeOf(Dog.prototype)); 279 | 280 | /////////////////////////////////////////////////////////////////////////////// 281 | // Use Inheritance So You Don't Repeat Yourself 282 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself 283 | // The eat method is repeated in both Cat and Bear. Edit the code in the spirit of DRY by moving the eat method to the Animal supertype. 284 | 285 | // function Cat(name) { 286 | // this.name = name; 287 | // } 288 | 289 | // Cat.prototype = { 290 | // constructor: Cat, 291 | // }; 292 | 293 | // function Bear(name) { 294 | // this.name = name; 295 | // } 296 | 297 | // Bear.prototype = { 298 | // constructor: Bear, 299 | // }; 300 | 301 | // function Animal() { } 302 | 303 | // Animal.prototype = { 304 | // constructor: Animal, 305 | // eat: function() { 306 | // console.log("nom nom nom"); 307 | // } 308 | // }; 309 | 310 | /////////////////////////////////////////////////////////////////////////////// 311 | // Inherit Behaviors from a Supertype 312 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/inherit-behaviors-from-a-supertype 313 | // Use Object.create to make two instances of Animal named duck and beagle. 314 | 315 | // function Animal() { } 316 | 317 | // Animal.prototype = { 318 | // constructor: Animal, 319 | // eat: function() { 320 | // console.log("nom nom nom"); 321 | // } 322 | // }; 323 | 324 | // Only change code below this line 325 | 326 | // let duck = Object.create(Animal.prototype); // Change this line 327 | // let beagle = Object.create(Animal.prototype); // Change this line 328 | // console.log(duck.eat()); 329 | // console.log(beagle); 330 | 331 | /////////////////////////////////////////////////////////////////////////////// 332 | // Set the Child's Prototype to an Instance of the Parent 333 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent 334 | // Modify the code so that instances of Dog inherit from Animal. 335 | 336 | // function Animal() { } 337 | 338 | // Animal.prototype = { 339 | // constructor: Animal, 340 | // eat: function() { 341 | // console.log("nom nom nom"); 342 | // } 343 | // }; 344 | 345 | // function Dog() { } 346 | 347 | // // Only change code below this line 348 | // Dog.prototype = Object.create(Animal.prototype); 349 | 350 | // let beagle = new Dog(); 351 | // console.log(beagle.eat()); 352 | 353 | /////////////////////////////////////////////////////////////////////////////// 354 | // Reset an Inherited Constructor Property 355 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/reset-an-inherited-constructor-property 356 | // Fix the code so duck.constructor and beagle.constructor return their respective constructors. 357 | 358 | // function Animal() { } 359 | // function Bird() { } 360 | // function Dog() { } 361 | 362 | // Bird.prototype = Object.create(Animal.prototype); 363 | // Dog.prototype = Object.create(Animal.prototype); 364 | 365 | // // Only change code below this line 366 | // Bird.prototype.constructor = Bird; 367 | // Dog.prototype.constructor = Dog; 368 | 369 | // let duck = new Bird(); 370 | // let beagle = new Dog(); 371 | // console.log(duck); 372 | // console.log(beagle); 373 | 374 | /////////////////////////////////////////////////////////////////////////////// 375 | // Add Methods After Inheritance 376 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance 377 | // Add all necessary code so the Dog object inherits from Animal and the Dog's prototype constructor is set to Dog. Then add a bark() method to the Dog object so that beagle can both eat() and bark(). The bark() method should print "Woof!" to the console. 378 | 379 | // function Animal() { } 380 | // Animal.prototype.eat = function() { console.log("nom nom nom"); }; 381 | 382 | // function Dog() { } 383 | 384 | // // Only change code below this line 385 | // Dog.prototype = Object.create(Animal.prototype); 386 | // Dog.prototype.constructor = Dog; 387 | 388 | // Dog.prototype.bark = function () { 389 | // console.log('Woof!'); 390 | // }; 391 | 392 | 393 | 394 | // // Only change code above this line 395 | 396 | // let beagle = new Dog(); 397 | // console.log(beagle.bark()); 398 | 399 | /////////////////////////////////////////////////////////////////////////////// 400 | // Override Inherited Methods 401 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods 402 | // Override the fly() method for Penguin so that it returns "Alas, this is a flightless bird." 403 | 404 | // function Bird() { } 405 | 406 | // Bird.prototype.fly = function() { return "I am flying!"; }; 407 | 408 | // function Penguin() { } 409 | // Penguin.prototype = Object.create(Bird.prototype); 410 | // Penguin.prototype.constructor = Penguin; 411 | 412 | // // Only change code below this line 413 | 414 | // Penguin.prototype.fly = function() { return "Alas, this is a flightless bird."; }; 415 | 416 | // // Only change code above this line 417 | 418 | // let penguin = new Penguin(); 419 | // console.log(penguin.fly()); 420 | 421 | /////////////////////////////////////////////////////////////////////////////// 422 | // Use a Mixin to Add Common Behavior Between Unrelated Objects 423 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-a-mixin-to-add-common-behavior-between-unrelated-objects 424 | 425 | // The flyMixin takes any object and gives it the fly method. 426 | 427 | // let bird = { 428 | // name: "Donald", 429 | // numLegs: 2 430 | // }; 431 | 432 | // let plane = { 433 | // model: "777", 434 | // numPassengers: 524 435 | // }; 436 | 437 | // flyMixin(bird); 438 | // flyMixin(plane); 439 | 440 | // Create a mixin named glideMixin that defines a method named glide. Then use the glideMixin to give both bird and boat the ability to glide. 441 | 442 | // let bird = { 443 | // name: "Donald", 444 | // numLegs: 2 445 | // }; 446 | 447 | // let boat = { 448 | // name: "Warrior", 449 | // type: "race-boat" 450 | // }; 451 | 452 | // // Only change code below this line 453 | // const glideMixin = obj => { 454 | // obj.glide = function () { 455 | // console.log('I can glide!'); 456 | // return 'I can glide!' 457 | // } 458 | // } 459 | 460 | // glideMixin(boat); 461 | // glideMixin(bird); 462 | // console.log(bird.glide()); 463 | // console.log(boat.glide()); 464 | 465 | /////////////////////////////////////////////////////////////////////////////// 466 | // Use Closure to Protect Properties Within an Object from Being Modified Externally 467 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-closure-to-protect-properties-within-an-object-from-being-modified-externally 468 | 469 | function Bird() { 470 | let hatchedEgg = 10; // private variable 471 | 472 | /* publicly available method that a bird object can use */ 473 | this.getHatchedEggCount = function() { 474 | return hatchedEgg; 475 | }; 476 | } 477 | let ducky = new Bird(); 478 | ducky.getHatchedEggCount(); // returns 10 479 | 480 | // Change how weight is declared in the Bird function so it is a private variable. Then, create a method getWeight that returns the value of weight 15. 481 | 482 | function Bird() { 483 | // private variable 484 | let weight = 15; 485 | 486 | // privileged public access 487 | this.getWeight = function () { 488 | console.log(weight); 489 | return weight; 490 | } 491 | } 492 | 493 | // const bird2 = new Bird(); 494 | // console.log(bird2); 495 | // console.log(bird2.getWeight()); 496 | 497 | /////////////////////////////////////////////////////////////////////////////// 498 | // Understand the Immediately Invoked Function Expression (IIFE) 499 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife 500 | 501 | (function () { 502 | console.log("Chirp, chirp!"); 503 | })(); // this is an anonymous function expression that executes right away 504 | // Outputs "Chirp, chirp!" immediately 505 | 506 | // Rewrite the function makeNest and remove its call so instead it's an anonymous immediately invoked function expression (IIFE). 507 | 508 | function makeNest() { 509 | console.log("A cozy nest is ready"); 510 | return "A cozy nest is ready"; 511 | } 512 | 513 | console.log(makeNest()); 514 | 515 | (function () { 516 | console.log("A cozy nest is ready"); 517 | return "A cozy nest is ready"; 518 | })(); 519 | 520 | /////////////////////////////////////////////////////////////////////////////// 521 | // Use an IIFE to Create a Module 522 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module 523 | 524 | let motionModule = (function () { 525 | return { 526 | glideMixin: function(obj) { 527 | obj.glide = function() { 528 | console.log("Gliding on the water"); 529 | }; 530 | }, 531 | flyMixin: function(obj) { 532 | obj.fly = function() { 533 | console.log("Flying, wooosh!"); 534 | }; 535 | } 536 | } 537 | })(); // The two parentheses cause the function to be immediately invoked 538 | 539 | // motionModule.glideMixin(duck); 540 | // duck.glide(); 541 | 542 | // Create a module named funModule to wrap the two mixins isCuteMixin and singMixin. funModule should return an object. 543 | 544 | // let singMixin = function(obj) { 545 | // obj.sing = function() { 546 | // console.log("Singing to an awesome tune"); 547 | // }; 548 | // }; 549 | 550 | const funModule = (function () { 551 | return { 552 | isCuteMixin: function (obj) { 553 | obj.isCute = function () { 554 | return true; 555 | } 556 | }, 557 | 558 | singMixin: function (obj) { 559 | obj.sing = function () { 560 | console.log("Singing to an awesome tune"); 561 | return "Singing to an awesome tune"; 562 | 563 | } 564 | } 565 | } 566 | })(); 567 | 568 | const duck = {}; 569 | 570 | // funModule.singMixin(duck); 571 | // console.log(duck.sing()); -------------------------------------------------------------------------------- /JavaScript Algorithms and Data Structures/3 - Regular-Expressions/index.js: -------------------------------------------------------------------------------- 1 | // Using the Test Method 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method 3 | 4 | // let testStr = "freeCodeCamp"; 5 | // let testRegex = /Code/; 6 | // testRegex.test(testStr); 7 | // // Returns true 8 | 9 | // let myString = "Hello, World!"; 10 | // let myRegex = /Hello/; 11 | // let result = myRegex.test(myString); // Change this line 12 | // console.log(result); 13 | 14 | //////////////////////////////////////////////////////////////////////////////////////// 15 | 16 | // Regular Expressions: Match Literal Strings 17 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings 18 | 19 | // let testStr = "Hello, my name is Kevin."; 20 | // let testRegex = /Kevin/; 21 | // testRegex.test(testStr); 22 | // // Returns true 23 | 24 | // let wrongRegex = /kevin/; 25 | // wrongRegex.test(testStr); 26 | // // Returns false 27 | 28 | // let waldoIsHiding = "Somewhere Waldo is hiding in this text."; 29 | // let waldoRegex = /Waldo/; // Change this line 30 | // let result = waldoRegex.test(waldoIsHiding); 31 | // console.log(result); 32 | 33 | //////////////////////////////////////////////////////////////////////////////////////// 34 | // Regular Expressions: Match a Literal String with Different Possibilities 35 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities 36 | 37 | // let petString = "James has a pet cat."; 38 | // let petRegex = /dog|bird|fish|cat/; // Change this line 39 | // let result = petRegex.test(petString); 40 | // console.log(result); 41 | 42 | 43 | //////////////////////////////////////////////////////////////////////////////////////// 44 | // Regular Expressions: Ignore Case While Matching 45 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching 46 | 47 | // let myString = "freeCodeCamp"; 48 | // let fccRegex = /freecodecamp/i; // Change this line 49 | // let result = fccRegex.test(myString); 50 | // console.log(result); 51 | 52 | //////////////////////////////////////////////////////////////////////////////////////// 53 | // Regular Expressions: Extract Matches 54 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/extract-matches 55 | 56 | // "Hello, World!".match(/Hello/); 57 | // // Returns ["Hello"] 58 | // let ourStr = "Regular expressions"; 59 | // let ourRegex = /expressions/; 60 | // ourStr.match(ourRegex); 61 | // // Returns ["expressions"] 62 | 63 | // 'string'.match(/regex/); 64 | // /regex/.test('string'); 65 | 66 | // let extractStr = "Extract the word 'coding' from this string."; 67 | // let codingRegex = /coding/; // Change this line 68 | // let result = extractStr.match(codingRegex); // Change this line 69 | 70 | // console.log(result); 71 | 72 | //////////////////////////////////////////////////////////////////////////////////////// 73 | // Regular Expressions: Find More Than the First Match 74 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match 75 | 76 | // let testStr = "Repeat, Repeat, Repeat"; 77 | // let ourRegex = /Repeat/; 78 | // testStr.match(ourRegex); 79 | // // Returns ["Repeat"] 80 | 81 | // let repeatRegex = /Repeat/g; 82 | // testStr.match(repeatRegex); 83 | // // Returns ["Repeat", "Repeat", "Repeat"] 84 | 85 | // let twinkleStar = "Twinkle, twinkle, little star"; 86 | // let starRegex = /twinkle/gi; // Change this line 87 | // let result = twinkleStar.match(starRegex); // Change this line 88 | // console.log(result); 89 | 90 | //////////////////////////////////////////////////////////////////////////////////////// 91 | // Regular Expressions: Match Anything with Wildcard Period 92 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period 93 | 94 | // let humStr = "I'll hum a song"; 95 | // let hugStr = "Bear hug"; 96 | // let huRegex = /hu./; 97 | // huRegex.test(humStr); // Returns true 98 | // huRegex.test(hugStr); // Returns true 99 | 100 | // let exampleStr = "Let's have fun with regular expressions!"; 101 | // let unRegex = /.un/; // Change this line 102 | // let result = unRegex.test(exampleStr); 103 | // console.log(result); 104 | 105 | //////////////////////////////////////////////////////////////////////////////////////// 106 | // Regular Expressions: Match Single Character with Multiple Possibilities 107 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities 108 | 109 | // let bigStr = "big"; 110 | // let bagStr = "bag"; 111 | // let bugStr = "bug"; 112 | // let bogStr = "bog"; 113 | // let bgRegex = /b[aiu]g/; 114 | // bigStr.match(bgRegex); // Returns ["big"] 115 | // bagStr.match(bgRegex); // Returns ["bag"] 116 | // bugStr.match(bgRegex); // Returns ["bug"] 117 | // bogStr.match(bgRegex); // Returns null 118 | 119 | // let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it."; 120 | // let vowelRegex = /[aeiou]/gi; // Change this line 121 | // let result = quoteSample.match(vowelRegex); // Change this line 122 | // console.log(result) 123 | 124 | //////////////////////////////////////////////////////////////////////////////////////// 125 | // Regular Expressions: Match Letters of the Alphabet 126 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet 127 | 128 | // let catStr = "cat"; 129 | // let batStr = "bat"; 130 | // let matStr = "mat"; 131 | // let bgRegex = /[a-e]at/; 132 | // catStr.match(bgRegex); // Returns ["cat"] 133 | // batStr.match(bgRegex); // Returns ["bat"] 134 | // matStr.match(bgRegex); // Returns null 135 | 136 | // let quoteSample = "The quick brown fox jumps over the lazy dog."; 137 | // let alphabetRegex = /[a-z]/gi; // Change this line 138 | // let result = quoteSample.match(alphabetRegex); // Change this line 139 | // console.log(result); 140 | 141 | //////////////////////////////////////////////////////////////////////////////////////// 142 | // Regular Expressions: Match Numbers and Letters of the Alphabet 143 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet 144 | 145 | // let jennyStr = "Jenny8675309"; 146 | // let myRegex = /[a-z0-9]/ig; 147 | // // matches all letters and numbers in jennyStr 148 | // jennyStr.match(myRegex); 149 | 150 | // let quoteSample = "Blueberry 3.141592653s are delicious."; 151 | // let myRegex = /[h-s2-6]/gi; // Change this line 152 | // let result = quoteSample.match(myRegex); // Change this line 153 | // console.log(result) 154 | 155 | //////////////////////////////////////////////////////////////////////////////////////// 156 | // Regular Expressions: Match Single Characters Not Specified 157 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified 158 | 159 | let quoteSampleMice = "3 blind mice."; 160 | let myRegexMice = /[^aeiou0-9]/gi; // Change this line 161 | let resultMice = quoteSampleMice.match(myRegexMice); // Change this line 162 | console.log(resultMice) 163 | 164 | //////////////////////////////////////////////////////////////////////////////////////// 165 | // Regular Expressions: Match Characters that Occur One or More Times 166 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times 167 | 168 | // let difficultSpelling = "Mississippi"; 169 | // let myRegex = /s+/gi; // Change this line 170 | // let result = difficultSpelling.match(myRegex); 171 | // console.log(result) 172 | 173 | //////////////////////////////////////////////////////////////////////////////////////// 174 | // Regular Expressions: Match Characters that Occur Zero or More Times 175 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times 176 | 177 | // let soccerWord = "gooooooooal!"; 178 | // let gPhrase = "gut feeling"; 179 | // let oPhrase = "over the moon"; 180 | // let goRegex = /go*/; 181 | // soccerWord.match(goRegex); // Returns ["goooooooo"] 182 | // gPhrase.match(goRegex); // Returns ["g"] 183 | // oPhrase.match(goRegex); // Returns null 184 | 185 | // let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!"; 186 | // Only change code below this line 187 | // let chewieRegex = /Aa*/; // Change this line 188 | // Only change code above this line 189 | 190 | // let result = chewieQuote.match(chewieRegex); 191 | // console.log(result) 192 | 193 | 194 | //////////////////////////////////////////////////////////////////////////////////////// 195 | // Regular Expressions: Find Characters with Lazy Matching 196 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching 197 | 198 | // let text = "

Winter is coming

"; 199 | // let myRegex = /<.[0-9]?>/; // Change this line 200 | // let result = text.match(myRegex); 201 | // console.log(result) 202 | 203 | 204 | //////////////////////////////////////////////////////////////////////////////////////// 205 | // Regular Expressions: Find One or More Criminals in a Hunt 206 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt 207 | 208 | // "z" 209 | // "zzzzzz" 210 | // "ABCzzzz" 211 | // "zzzzABC" 212 | // "abczzzzzzzzzzzzzzzzzzzzzabc" 213 | 214 | // "" 215 | // "ABC" 216 | // "abcabc" 217 | 218 | // Write a greedy regex that finds one or more criminals within a group of other people. A criminal is represented by the capital letter C. 219 | 220 | // let test1 = "C"; 221 | // let test2 = "CC"; 222 | // let test3 = "P1P5P4CCCP2P6P3"; 223 | // let test4 = "P6P2P7P4P5CCCCCP3P1"; 224 | // let test5 = ""; 225 | // let test6 = "P1P2P3"; 226 | // let test7 = "P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3"; 227 | 228 | // let reCriminals = /C+/g; // Change this line 229 | 230 | // console.log(test1.match(reCriminals)); 231 | // console.log(test2.match(reCriminals)); 232 | // console.log(test3.match(reCriminals)); 233 | // console.log(test4.match(reCriminals)); 234 | // console.log(test5.match(reCriminals)); 235 | // console.log(test6.match(reCriminals)); 236 | // console.log(test7.match(reCriminals)); 237 | 238 | 239 | //////////////////////////////////////////////////////////////////////////////////////// 240 | // Regular Expressions: Match Beginning String Patterns 241 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns 242 | 243 | // let firstString = "Ricky is first and can be found."; 244 | // let firstRegex = /^Ricky/; 245 | // firstRegex.test(firstString); 246 | // // Returns true 247 | // let notFirst = "You can't find Ricky now."; 248 | // firstRegex.test(notFirst); 249 | // // Returns false 250 | 251 | // let rickyAndCal = "Cal and Ricky both like racing."; 252 | // let calRegex = /^Cal/; // Change this line 253 | // let result = calRegex.test(rickyAndCal); 254 | // console.log(result) 255 | 256 | 257 | //////////////////////////////////////////////////////////////////////////////////////// 258 | // Regular Expressions: Match Ending String Patterns 259 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns 260 | 261 | // let theEnding = "This is a never ending story"; 262 | // let storyRegex = /story$/; 263 | // storyRegex.test(theEnding); 264 | // // Returns true 265 | // let noEnding = "Sometimes a story will have to end"; 266 | // storyRegex.test(noEnding); 267 | // // Returns false 268 | 269 | // let caboose = "The last car on a train is the caboose"; 270 | // let lastRegex = /caboose$/; // Change this line 271 | // let result = lastRegex.test(caboose); 272 | // console.log(result) 273 | 274 | 275 | //////////////////////////////////////////////////////////////////////////////////////// 276 | // Regular Expressions: Match All Letters and Numbers 277 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers 278 | 279 | // let longHand = /[A-Za-z0-9_]+/; 280 | // let shortHand = /\w+/; 281 | // let numbers = "42"; 282 | // let varNames = "important_var"; 283 | // longHand.test(numbers); // Returns true 284 | // shortHand.test(numbers); // Returns true 285 | // longHand.test(varNames); // Returns true 286 | // shortHand.test(varNames); // Returns true 287 | 288 | // let quoteSample = "The five boxing wizards jump quickly."; 289 | // let alphabetRegexV2 = /[A-Za-z0-9_]/g; // Change this line 290 | // // let alphabetRegexV2 = /\w/g; // Change this line 291 | // let result = quoteSample.match(alphabetRegexV2); 292 | // console.log(result) 293 | 294 | //////////////////////////////////////////////////////////////////////////////////////// 295 | // Regular Expressions: Match Everything But Letters and Numbers 296 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers 297 | 298 | // let shortHand = /\W/; 299 | // let numbers = "42%"; 300 | // let sentence = "Coding!"; 301 | // numbers.match(shortHand); // Returns ["%"] 302 | // sentence.match(shortHand); // Returns ["!"] 303 | 304 | // let quoteSample = "The five boxing wizards jump quickly."; 305 | // let nonAlphabetRegex = /\W/g; // Change this line 306 | // let result = quoteSample.match(nonAlphabetRegex).length; 307 | // console.log(result); 308 | 309 | //////////////////////////////////////////////////////////////////////////////////////// 310 | // Regular Expressions: Match All Numbers 311 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers 312 | 313 | // let movieName = "2001: A Space Odyssey"; 314 | // let numRegex = /\d/g; // Change this line 315 | // let result = movieName.match(numRegex).length; 316 | // console.log(result); 317 | 318 | //////////////////////////////////////////////////////////////////////////////////////// 319 | // Regular Expressions: Match All Non-Numbers 320 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers 321 | 322 | let movieName = "2001: A Space Odyssey"; 323 | let noNumRegex = /\D/g; // Change this line 324 | let resultMovie = movieName.match(noNumRegex); 325 | console.log(resultMovie); 326 | 327 | //////////////////////////////////////////////////////////////////////////////////////// 328 | // Regular Expressions: Restrict Possible Usernames 329 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames 330 | 331 | let username1 = "JACK"; 332 | let username2 = "J"; 333 | let username3 = "Jo"; 334 | let username4 = "Oceans11"; 335 | let username5 = "RegexGuru"; 336 | let username6 = "007"; 337 | let username7 = "9"; 338 | let username8 = "A1"; 339 | let username9 = "BadUs3rnam3"; 340 | let username10 = "Z97"; 341 | let username11 = "c57bT3"; 342 | 343 | let userCheck = /^[a-z][a-z]+\d*$|^[a-z]\d\d+$/i; // Change this line 344 | 345 | let matching1 = username1.match(userCheck); 346 | let matching2 = username2.match(userCheck); 347 | let matching3 = username3.match(userCheck); 348 | let matching4 = username4.match(userCheck); 349 | let matching5 = username5.match(userCheck); 350 | let matching6 = username6.match(userCheck); 351 | let matching7 = username7.match(userCheck); 352 | let matching8 = username8.match(userCheck); 353 | let matching9 = username9.match(userCheck); 354 | let matching10 = username10.match(userCheck); 355 | let matching11 = username11.match(userCheck); 356 | 357 | console.log(matching1, userCheck.test(username1)) 358 | console.log(matching2, userCheck.test(username2)) // null 359 | console.log(matching3, userCheck.test(username3)) 360 | console.log(matching4, userCheck.test(username4)) 361 | console.log(matching5, userCheck.test(username5)) 362 | console.log(matching6, userCheck.test(username6)) // null 363 | console.log(matching7, userCheck.test(username7)) // null 364 | console.log(matching8, userCheck.test(username8)) // null 365 | console.log(matching9, userCheck.test(username9)) // null 366 | console.log(matching10, userCheck.test(username10)) 367 | console.log(matching11, userCheck.test(username11)) //null 368 | 369 | 370 | //////////////////////////////////////////////////////////////////////////////////////// 371 | // Regular Expressions: Match Whitespace 372 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-whitespace 373 | 374 | // let whiteSpace = "Whitespace. Whitespace everywhere!" 375 | // let spaceRegex = /\s/g; 376 | // whiteSpace.match(spaceRegex); 377 | // // Returns [" ", " "] 378 | 379 | // let sample = "Whitespace is important in separating words"; 380 | // let countWhiteSpace = /\s/g; // Change this line 381 | // let result = sample.match(countWhiteSpace); 382 | // console.log(result) 383 | 384 | //////////////////////////////////////////////////////////////////////////////////////// 385 | // Regular Expressions: Match Non-Whitespace Characters 386 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters 387 | 388 | // let whiteSpace = "Whitespace. Whitespace everywhere!" 389 | // let nonSpaceRegex = /\S/g; 390 | // whiteSpace.match(nonSpaceRegex).length; // Returns 32 391 | 392 | // let sample = "Whitespace is important in separating words"; 393 | // let countNonWhiteSpace = /\S/g; // Change this line 394 | // let result = sample.match(countNonWhiteSpace); 395 | // console.log(result) 396 | 397 | //////////////////////////////////////////////////////////////////////////////////////// 398 | // Regular Expressions: Specify Upper and Lower Number of Matches 399 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches 400 | 401 | // let A4 = "aaaah"; 402 | // let A2 = "aah"; 403 | // let multipleA = /a{3,5}h/; 404 | // multipleA.test(A4); // Returns true 405 | // multipleA.test(A2); // Returns false 406 | 407 | // Change the regex ohRegex to match the entire phrase "Oh no" only when it has 3 to 6 letter h's. 408 | 409 | // let ohStr = "Ohhh no"; 410 | // let ohRegex = /Oh{3,6} no/; // Change this line 411 | // let result = ohRegex.test(ohStr); 412 | // console.log(result) 413 | 414 | //////////////////////////////////////////////////////////////////////////////////////// 415 | // Regular Expressions: Specify Only the Lower Number of Matches 416 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches 417 | 418 | // let A4 = "haaaah"; 419 | // let A2 = "haah"; 420 | // let A100 = "h" + "a".repeat(100) + "h"; 421 | // let multipleA = /ha{3,}h/; 422 | // multipleA.test(A4); // Returns true 423 | // multipleA.test(A2); // Returns false 424 | // multipleA.test(A100); // Returns true 425 | 426 | // Change the regex haRegex to match the word "Hazzah" only when it has four or more letter z's. 427 | 428 | // let haStr = "Hazzzzah"; 429 | // let haRegex = /Haz{4,}ah/; // Change this line 430 | // let result = haRegex.test(haStr); 431 | // console.log(result) 432 | 433 | //////////////////////////////////////////////////////////////////////////////////////// 434 | // Regular Expressions: Specify Exact Number of Matches 435 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches 436 | 437 | // let A4 = "haaaah"; 438 | // let A3 = "haaah"; 439 | // let A100 = "h" + "a".repeat(100) + "h"; 440 | // let multipleHA = /ha{3}h/; 441 | // multipleHA.test(A4); // Returns false 442 | // multipleHA.test(A3); // Returns true 443 | // multipleHA.test(A100); // Returns false 444 | 445 | // Change the regex timRegex to match the word "Timber" only when it has four letter m's. 446 | 447 | // let timStr = "Timmmmber"; 448 | // let timRegex = /Tim{4}ber/; // Change this line 449 | // let result = timRegex.test(timStr); 450 | // console.log(result) 451 | 452 | //////////////////////////////////////////////////////////////////////////////////////// 453 | // Regular Expressions: Check for All or None 454 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none 455 | 456 | // let american = "color"; 457 | // let british = "colour"; 458 | // let rainbowRegex= /colou?r/; 459 | // rainbowRegex.test(american); // Returns true 460 | // rainbowRegex.test(british); // Returns true 461 | 462 | // Change the regex favRegex to match both the American English (favorite) and the British English (favourite) version of the word. 463 | 464 | // let favWord = "favorite"; 465 | // let favRegex = /favou?rite/; // Change this line 466 | // let result = favRegex.test(favWord); 467 | // console.log(result) 468 | 469 | //////////////////////////////////////////////////////////////////////////////////////// 470 | // Regular Expressions: Positive and Negative Lookahead 471 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead 472 | 473 | // let quit = "qu"; 474 | // let noquit = "qt"; 475 | // let quRegex= /q(?=u)/; 476 | // let qRegex = /q(?!u)/; 477 | // quit.match(quRegex); // Returns ["q"] 478 | // noquit.match(qRegex); // Returns ["q"] 479 | 480 | // let password = "abc123"; 481 | // let checkPass = /(?=\w{3,6})(?=\D*\d)/; 482 | // checkPass.test(password); // Returns true 483 | 484 | // Use lookaheads in the pwRegex to match passwords that are greater than 5 characters long, do not begin with numbers, and have two consecutive digits. 485 | 486 | // let sampleWord = "astronaut"; 487 | // let pwRegex = /^\D(?=\w{5,})(?=\w*\d\d+)/; // Change this line 488 | // freeCodeCamp solution 489 | // var pwRegex = /^\D(?=\w{5})(?=\w*\d{2})/; 490 | // let result = pwRegex.test(sampleWord); 491 | 492 | // console.log(result) 493 | 494 | //////////////////////////////////////////////////////////////////////////////////////// 495 | // Regular Expressions: Check For Mixed Grouping of Characters 496 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/check-for-mixed-grouping-of-characters 497 | 498 | // let testStr = "Pumpkin"; 499 | // let testRegex = /P(engu|umpk)in/; 500 | // testRegex.test(testStr); 501 | // // Returns true 502 | 503 | // Fix the regex so that it checks for the names of Franklin Roosevelt or Eleanor Roosevelt in a case sensitive manner and it should make concessions for middle names. 504 | 505 | // Then fix the code so that the regex that you have created is checked against myString and either true or false is returned depending on whether the regex matches. 506 | 507 | // let myStringPrez = "Eleanor Roosevelt"; 508 | // let myRegexPrez = /(Franklin|Eleanor)(\D*)Roosevelt/; // Change this line 509 | // let resultPrez = myRegexPrez.test(myStringPrez); // Change this line 510 | // console.log(resultPrez); 511 | // After passing the challenge experiment with myString and see how the grouping works 512 | 513 | 514 | //////////////////////////////////////////////////////////////////////////////////////// 515 | // Regular Expressions: Reuse Patterns Using Capture Groups 516 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups 517 | 518 | // let repeatStr = "regex regex"; 519 | // let repeatRegex = /(\w+)\s\1/; 520 | // repeatRegex.test(repeatStr); // Returns true 521 | // repeatStr.match(repeatRegex); // Returns ["regex regex", "regex"] 522 | 523 | // Using the .match() method on a string will return an array with the string it matches, along with its capture group. 524 | 525 | // Use capture groups in reRegex to match numbers that are repeated only three times in a string, each separated by a space. 526 | 527 | // let repeatNum = "42 42 42"; 528 | // let reRegex = /^(\d+\s*)/; // Change this line 529 | // // freeCodeCamp answer 530 | // let reRegexfCC = /^(\d+)\s\1\s\1$/; 531 | // let result = reRegex.test(repeatNum); 532 | // console.log(result); 533 | // console.log(reRegexfCC.test(repeatNum)); 534 | // console.log(repeatNum.match(reRegexfCC)); 535 | 536 | //////////////////////////////////////////////////////////////////////////////////////// 537 | // Regular Expressions: Use Capture Groups to Search and Replace 538 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace 539 | 540 | // let wrongText = "The sky is silver."; 541 | // let silverRegex = /silver/; 542 | // wrongText.replace(silverRegex, "blue"); 543 | // // Returns "The sky is blue." 544 | 545 | // "Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1'); 546 | // // Returns "Camp Code" 547 | 548 | // Write a regex fixRegex using three capture groups that will search for each word in the string "one two three". Then update the replaceText variable to replace "one two three" with the string "three two one" and assign the result to the result variable. Make sure you are utilizing capture groups in the replacement string using the dollar sign ($) syntax. 549 | 550 | // let str = "one two three"; 551 | // let fixRegex = /(\w+)\s(\w+)\s(\w+)/; // Change this line 552 | // let replaceText = "$3 $2 $1"; // Change this line 553 | // let result = str.replace(fixRegex, replaceText); 554 | // console.log(result); 555 | 556 | //////////////////////////////////////////////////////////////////////////////////////// 557 | // Regular Expressions: Remove Whitespace from Start and End 558 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end 559 | 560 | // Write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings. 561 | 562 | // Note: The String.prototype.trim() method would work here, but you'll need to complete this challenge using regular expressions. 563 | 564 | let hello = " Hello, World! "; 565 | let wsRegex = /(\s\s+)/g; // Change this line 566 | let result = hello.replace(wsRegex, ''); // Change this line 567 | console.log(result); 568 | console.log('Hello, World!') 569 | 570 | //////////////////////////////////////////////////////////////////////////////////////// 571 | -------------------------------------------------------------------------------- /JavaScript-Algorithms-and-Data-Structures/3 - Regular-Expressions/index.js: -------------------------------------------------------------------------------- 1 | // Using the Test Method 2 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method 3 | 4 | // let testStr = "freeCodeCamp"; 5 | // let testRegex = /Code/; 6 | // testRegex.test(testStr); 7 | // // Returns true 8 | 9 | // let myString = "Hello, World!"; 10 | // let myRegex = /Hello/; 11 | // let result = myRegex.test(myString); // Change this line 12 | // console.log(result); 13 | 14 | //////////////////////////////////////////////////////////////////////////////////////// 15 | 16 | // Regular Expressions: Match Literal Strings 17 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings 18 | 19 | // let testStr = "Hello, my name is Kevin."; 20 | // let testRegex = /Kevin/; 21 | // testRegex.test(testStr); 22 | // // Returns true 23 | 24 | // let wrongRegex = /kevin/; 25 | // wrongRegex.test(testStr); 26 | // // Returns false 27 | 28 | // let waldoIsHiding = "Somewhere Waldo is hiding in this text."; 29 | // let waldoRegex = /Waldo/; // Change this line 30 | // let result = waldoRegex.test(waldoIsHiding); 31 | // console.log(result); 32 | 33 | //////////////////////////////////////////////////////////////////////////////////////// 34 | // Regular Expressions: Match a Literal String with Different Possibilities 35 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities 36 | 37 | // let petString = "James has a pet cat."; 38 | // let petRegex = /dog|bird|fish|cat/; // Change this line 39 | // let result = petRegex.test(petString); 40 | // console.log(result); 41 | 42 | 43 | //////////////////////////////////////////////////////////////////////////////////////// 44 | // Regular Expressions: Ignore Case While Matching 45 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching 46 | 47 | // let myString = "freeCodeCamp"; 48 | // let fccRegex = /freecodecamp/i; // Change this line 49 | // let result = fccRegex.test(myString); 50 | // console.log(result); 51 | 52 | //////////////////////////////////////////////////////////////////////////////////////// 53 | // Regular Expressions: Extract Matches 54 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/extract-matches 55 | 56 | // "Hello, World!".match(/Hello/); 57 | // // Returns ["Hello"] 58 | // let ourStr = "Regular expressions"; 59 | // let ourRegex = /expressions/; 60 | // ourStr.match(ourRegex); 61 | // // Returns ["expressions"] 62 | 63 | // 'string'.match(/regex/); 64 | // /regex/.test('string'); 65 | 66 | // let extractStr = "Extract the word 'coding' from this string."; 67 | // let codingRegex = /coding/; // Change this line 68 | // let result = extractStr.match(codingRegex); // Change this line 69 | 70 | // console.log(result); 71 | 72 | //////////////////////////////////////////////////////////////////////////////////////// 73 | // Regular Expressions: Find More Than the First Match 74 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match 75 | 76 | // let testStr = "Repeat, Repeat, Repeat"; 77 | // let ourRegex = /Repeat/; 78 | // testStr.match(ourRegex); 79 | // // Returns ["Repeat"] 80 | 81 | // let repeatRegex = /Repeat/g; 82 | // testStr.match(repeatRegex); 83 | // // Returns ["Repeat", "Repeat", "Repeat"] 84 | 85 | // let twinkleStar = "Twinkle, twinkle, little star"; 86 | // let starRegex = /twinkle/gi; // Change this line 87 | // let result = twinkleStar.match(starRegex); // Change this line 88 | // console.log(result); 89 | 90 | //////////////////////////////////////////////////////////////////////////////////////// 91 | // Regular Expressions: Match Anything with Wildcard Period 92 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period 93 | 94 | // let humStr = "I'll hum a song"; 95 | // let hugStr = "Bear hug"; 96 | // let huRegex = /hu./; 97 | // huRegex.test(humStr); // Returns true 98 | // huRegex.test(hugStr); // Returns true 99 | 100 | // let exampleStr = "Let's have fun with regular expressions!"; 101 | // let unRegex = /.un/; // Change this line 102 | // let result = unRegex.test(exampleStr); 103 | // console.log(result); 104 | 105 | //////////////////////////////////////////////////////////////////////////////////////// 106 | // Regular Expressions: Match Single Character with Multiple Possibilities 107 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities 108 | 109 | // let bigStr = "big"; 110 | // let bagStr = "bag"; 111 | // let bugStr = "bug"; 112 | // let bogStr = "bog"; 113 | // let bgRegex = /b[aiu]g/; 114 | // bigStr.match(bgRegex); // Returns ["big"] 115 | // bagStr.match(bgRegex); // Returns ["bag"] 116 | // bugStr.match(bgRegex); // Returns ["bug"] 117 | // bogStr.match(bgRegex); // Returns null 118 | 119 | // let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it."; 120 | // let vowelRegex = /[aeiou]/gi; // Change this line 121 | // let result = quoteSample.match(vowelRegex); // Change this line 122 | // console.log(result) 123 | 124 | //////////////////////////////////////////////////////////////////////////////////////// 125 | // Regular Expressions: Match Letters of the Alphabet 126 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet 127 | 128 | // let catStr = "cat"; 129 | // let batStr = "bat"; 130 | // let matStr = "mat"; 131 | // let bgRegex = /[a-e]at/; 132 | // catStr.match(bgRegex); // Returns ["cat"] 133 | // batStr.match(bgRegex); // Returns ["bat"] 134 | // matStr.match(bgRegex); // Returns null 135 | 136 | // let quoteSample = "The quick brown fox jumps over the lazy dog."; 137 | // let alphabetRegex = /[a-z]/gi; // Change this line 138 | // let result = quoteSample.match(alphabetRegex); // Change this line 139 | // console.log(result); 140 | 141 | //////////////////////////////////////////////////////////////////////////////////////// 142 | // Regular Expressions: Match Numbers and Letters of the Alphabet 143 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet 144 | 145 | // let jennyStr = "Jenny8675309"; 146 | // let myRegex = /[a-z0-9]/ig; 147 | // // matches all letters and numbers in jennyStr 148 | // jennyStr.match(myRegex); 149 | 150 | // let quoteSample = "Blueberry 3.141592653s are delicious."; 151 | // let myRegex = /[h-s2-6]/gi; // Change this line 152 | // let result = quoteSample.match(myRegex); // Change this line 153 | // console.log(result) 154 | 155 | //////////////////////////////////////////////////////////////////////////////////////// 156 | // Regular Expressions: Match Single Characters Not Specified 157 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified 158 | 159 | let quoteSampleMice = "3 blind mice."; 160 | let myRegexMice = /[^aeiou0-9]/gi; // Change this line 161 | let resultMice = quoteSampleMice.match(myRegexMice); // Change this line 162 | console.log(resultMice) 163 | 164 | //////////////////////////////////////////////////////////////////////////////////////// 165 | // Regular Expressions: Match Characters that Occur One or More Times 166 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times 167 | 168 | // let difficultSpelling = "Mississippi"; 169 | // let myRegex = /s+/gi; // Change this line 170 | // let result = difficultSpelling.match(myRegex); 171 | // console.log(result) 172 | 173 | //////////////////////////////////////////////////////////////////////////////////////// 174 | // Regular Expressions: Match Characters that Occur Zero or More Times 175 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times 176 | 177 | // let soccerWord = "gooooooooal!"; 178 | // let gPhrase = "gut feeling"; 179 | // let oPhrase = "over the moon"; 180 | // let goRegex = /go*/; 181 | // soccerWord.match(goRegex); // Returns ["goooooooo"] 182 | // gPhrase.match(goRegex); // Returns ["g"] 183 | // oPhrase.match(goRegex); // Returns null 184 | 185 | // let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!"; 186 | // Only change code below this line 187 | // let chewieRegex = /Aa*/; // Change this line 188 | // Only change code above this line 189 | 190 | // let result = chewieQuote.match(chewieRegex); 191 | // console.log(result) 192 | 193 | 194 | //////////////////////////////////////////////////////////////////////////////////////// 195 | // Regular Expressions: Find Characters with Lazy Matching 196 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching 197 | 198 | // let text = "

Winter is coming

"; 199 | // let myRegex = /<.[0-9]?>/; // Change this line 200 | // let result = text.match(myRegex); 201 | // console.log(result) 202 | 203 | 204 | //////////////////////////////////////////////////////////////////////////////////////// 205 | // Regular Expressions: Find One or More Criminals in a Hunt 206 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt 207 | 208 | // "z" 209 | // "zzzzzz" 210 | // "ABCzzzz" 211 | // "zzzzABC" 212 | // "abczzzzzzzzzzzzzzzzzzzzzabc" 213 | 214 | // "" 215 | // "ABC" 216 | // "abcabc" 217 | 218 | // Write a greedy regex that finds one or more criminals within a group of other people. A criminal is represented by the capital letter C. 219 | 220 | // let test1 = "C"; 221 | // let test2 = "CC"; 222 | // let test3 = "P1P5P4CCCP2P6P3"; 223 | // let test4 = "P6P2P7P4P5CCCCCP3P1"; 224 | // let test5 = ""; 225 | // let test6 = "P1P2P3"; 226 | // let test7 = "P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3"; 227 | 228 | // let reCriminals = /C+/g; // Change this line 229 | 230 | // console.log(test1.match(reCriminals)); 231 | // console.log(test2.match(reCriminals)); 232 | // console.log(test3.match(reCriminals)); 233 | // console.log(test4.match(reCriminals)); 234 | // console.log(test5.match(reCriminals)); 235 | // console.log(test6.match(reCriminals)); 236 | // console.log(test7.match(reCriminals)); 237 | 238 | 239 | //////////////////////////////////////////////////////////////////////////////////////// 240 | // Regular Expressions: Match Beginning String Patterns 241 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns 242 | 243 | // let firstString = "Ricky is first and can be found."; 244 | // let firstRegex = /^Ricky/; 245 | // firstRegex.test(firstString); 246 | // // Returns true 247 | // let notFirst = "You can't find Ricky now."; 248 | // firstRegex.test(notFirst); 249 | // // Returns false 250 | 251 | // let rickyAndCal = "Cal and Ricky both like racing."; 252 | // let calRegex = /^Cal/; // Change this line 253 | // let result = calRegex.test(rickyAndCal); 254 | // console.log(result) 255 | 256 | 257 | //////////////////////////////////////////////////////////////////////////////////////// 258 | // Regular Expressions: Match Ending String Patterns 259 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns 260 | 261 | // let theEnding = "This is a never ending story"; 262 | // let storyRegex = /story$/; 263 | // storyRegex.test(theEnding); 264 | // // Returns true 265 | // let noEnding = "Sometimes a story will have to end"; 266 | // storyRegex.test(noEnding); 267 | // // Returns false 268 | 269 | // let caboose = "The last car on a train is the caboose"; 270 | // let lastRegex = /caboose$/; // Change this line 271 | // let result = lastRegex.test(caboose); 272 | // console.log(result) 273 | 274 | 275 | //////////////////////////////////////////////////////////////////////////////////////// 276 | // Regular Expressions: Match All Letters and Numbers 277 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers 278 | 279 | // let longHand = /[A-Za-z0-9_]+/; 280 | // let shortHand = /\w+/; 281 | // let numbers = "42"; 282 | // let varNames = "important_var"; 283 | // longHand.test(numbers); // Returns true 284 | // shortHand.test(numbers); // Returns true 285 | // longHand.test(varNames); // Returns true 286 | // shortHand.test(varNames); // Returns true 287 | 288 | // let quoteSample = "The five boxing wizards jump quickly."; 289 | // let alphabetRegexV2 = /[A-Za-z0-9_]/g; // Change this line 290 | // // let alphabetRegexV2 = /\w/g; // Change this line 291 | // let result = quoteSample.match(alphabetRegexV2); 292 | // console.log(result) 293 | 294 | //////////////////////////////////////////////////////////////////////////////////////// 295 | // Regular Expressions: Match Everything But Letters and Numbers 296 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers 297 | 298 | // let shortHand = /\W/; 299 | // let numbers = "42%"; 300 | // let sentence = "Coding!"; 301 | // numbers.match(shortHand); // Returns ["%"] 302 | // sentence.match(shortHand); // Returns ["!"] 303 | 304 | // let quoteSample = "The five boxing wizards jump quickly."; 305 | // let nonAlphabetRegex = /\W/g; // Change this line 306 | // let result = quoteSample.match(nonAlphabetRegex).length; 307 | // console.log(result); 308 | 309 | //////////////////////////////////////////////////////////////////////////////////////// 310 | // Regular Expressions: Match All Numbers 311 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers 312 | 313 | // let movieName = "2001: A Space Odyssey"; 314 | // let numRegex = /\d/g; // Change this line 315 | // let result = movieName.match(numRegex).length; 316 | // console.log(result); 317 | 318 | //////////////////////////////////////////////////////////////////////////////////////// 319 | // Regular Expressions: Match All Non-Numbers 320 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers 321 | 322 | let movieName = "2001: A Space Odyssey"; 323 | let noNumRegex = /\D/g; // Change this line 324 | let resultMovie = movieName.match(noNumRegex); 325 | console.log(resultMovie); 326 | 327 | //////////////////////////////////////////////////////////////////////////////////////// 328 | // Regular Expressions: Restrict Possible Usernames 329 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames 330 | 331 | let username1 = "JACK"; 332 | let username2 = "J"; 333 | let username3 = "Jo"; 334 | let username4 = "Oceans11"; 335 | let username5 = "RegexGuru"; 336 | let username6 = "007"; 337 | let username7 = "9"; 338 | let username8 = "A1"; 339 | let username9 = "BadUs3rnam3"; 340 | let username10 = "Z97"; 341 | let username11 = "c57bT3"; 342 | 343 | let userCheck = /^[a-z][a-z]+\d*$|^[a-z]\d\d+$/i; // Change this line 344 | 345 | let matching1 = username1.match(userCheck); 346 | let matching2 = username2.match(userCheck); 347 | let matching3 = username3.match(userCheck); 348 | let matching4 = username4.match(userCheck); 349 | let matching5 = username5.match(userCheck); 350 | let matching6 = username6.match(userCheck); 351 | let matching7 = username7.match(userCheck); 352 | let matching8 = username8.match(userCheck); 353 | let matching9 = username9.match(userCheck); 354 | let matching10 = username10.match(userCheck); 355 | let matching11 = username11.match(userCheck); 356 | 357 | console.log(matching1, userCheck.test(username1)) 358 | console.log(matching2, userCheck.test(username2)) // null 359 | console.log(matching3, userCheck.test(username3)) 360 | console.log(matching4, userCheck.test(username4)) 361 | console.log(matching5, userCheck.test(username5)) 362 | console.log(matching6, userCheck.test(username6)) // null 363 | console.log(matching7, userCheck.test(username7)) // null 364 | console.log(matching8, userCheck.test(username8)) // null 365 | console.log(matching9, userCheck.test(username9)) // null 366 | console.log(matching10, userCheck.test(username10)) 367 | console.log(matching11, userCheck.test(username11)) //null 368 | 369 | 370 | //////////////////////////////////////////////////////////////////////////////////////// 371 | // Regular Expressions: Match Whitespace 372 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-whitespace 373 | 374 | // let whiteSpace = "Whitespace. Whitespace everywhere!" 375 | // let spaceRegex = /\s/g; 376 | // whiteSpace.match(spaceRegex); 377 | // // Returns [" ", " "] 378 | 379 | // let sample = "Whitespace is important in separating words"; 380 | // let countWhiteSpace = /\s/g; // Change this line 381 | // let result = sample.match(countWhiteSpace); 382 | // console.log(result) 383 | 384 | //////////////////////////////////////////////////////////////////////////////////////// 385 | // Regular Expressions: Match Non-Whitespace Characters 386 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters 387 | 388 | // let whiteSpace = "Whitespace. Whitespace everywhere!" 389 | // let nonSpaceRegex = /\S/g; 390 | // whiteSpace.match(nonSpaceRegex).length; // Returns 32 391 | 392 | // let sample = "Whitespace is important in separating words"; 393 | // let countNonWhiteSpace = /\S/g; // Change this line 394 | // let result = sample.match(countNonWhiteSpace); 395 | // console.log(result) 396 | 397 | //////////////////////////////////////////////////////////////////////////////////////// 398 | // Regular Expressions: Specify Upper and Lower Number of Matches 399 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches 400 | 401 | // let A4 = "aaaah"; 402 | // let A2 = "aah"; 403 | // let multipleA = /a{3,5}h/; 404 | // multipleA.test(A4); // Returns true 405 | // multipleA.test(A2); // Returns false 406 | 407 | // Change the regex ohRegex to match the entire phrase "Oh no" only when it has 3 to 6 letter h's. 408 | 409 | // let ohStr = "Ohhh no"; 410 | // let ohRegex = /Oh{3,6} no/; // Change this line 411 | // let result = ohRegex.test(ohStr); 412 | // console.log(result) 413 | 414 | //////////////////////////////////////////////////////////////////////////////////////// 415 | // Regular Expressions: Specify Only the Lower Number of Matches 416 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches 417 | 418 | // let A4 = "haaaah"; 419 | // let A2 = "haah"; 420 | // let A100 = "h" + "a".repeat(100) + "h"; 421 | // let multipleA = /ha{3,}h/; 422 | // multipleA.test(A4); // Returns true 423 | // multipleA.test(A2); // Returns false 424 | // multipleA.test(A100); // Returns true 425 | 426 | // Change the regex haRegex to match the word "Hazzah" only when it has four or more letter z's. 427 | 428 | // let haStr = "Hazzzzah"; 429 | // let haRegex = /Haz{4,}ah/; // Change this line 430 | // let result = haRegex.test(haStr); 431 | // console.log(result) 432 | 433 | //////////////////////////////////////////////////////////////////////////////////////// 434 | // Regular Expressions: Specify Exact Number of Matches 435 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches 436 | 437 | // let A4 = "haaaah"; 438 | // let A3 = "haaah"; 439 | // let A100 = "h" + "a".repeat(100) + "h"; 440 | // let multipleHA = /ha{3}h/; 441 | // multipleHA.test(A4); // Returns false 442 | // multipleHA.test(A3); // Returns true 443 | // multipleHA.test(A100); // Returns false 444 | 445 | // Change the regex timRegex to match the word "Timber" only when it has four letter m's. 446 | 447 | // let timStr = "Timmmmber"; 448 | // let timRegex = /Tim{4}ber/; // Change this line 449 | // let result = timRegex.test(timStr); 450 | // console.log(result) 451 | 452 | //////////////////////////////////////////////////////////////////////////////////////// 453 | // Regular Expressions: Check for All or None 454 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none 455 | 456 | // let american = "color"; 457 | // let british = "colour"; 458 | // let rainbowRegex= /colou?r/; 459 | // rainbowRegex.test(american); // Returns true 460 | // rainbowRegex.test(british); // Returns true 461 | 462 | // Change the regex favRegex to match both the American English (favorite) and the British English (favourite) version of the word. 463 | 464 | // let favWord = "favorite"; 465 | // let favRegex = /favou?rite/; // Change this line 466 | // let result = favRegex.test(favWord); 467 | // console.log(result) 468 | 469 | //////////////////////////////////////////////////////////////////////////////////////// 470 | // Regular Expressions: Positive and Negative Lookahead 471 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead 472 | 473 | // let quit = "qu"; 474 | // let noquit = "qt"; 475 | // let quRegex= /q(?=u)/; 476 | // let qRegex = /q(?!u)/; 477 | // quit.match(quRegex); // Returns ["q"] 478 | // noquit.match(qRegex); // Returns ["q"] 479 | 480 | // let password = "abc123"; 481 | // let checkPass = /(?=\w{3,6})(?=\D*\d)/; 482 | // checkPass.test(password); // Returns true 483 | 484 | // Use lookaheads in the pwRegex to match passwords that are greater than 5 characters long, do not begin with numbers, and have two consecutive digits. 485 | 486 | // let sampleWord = "astronaut"; 487 | // let pwRegex = /^\D(?=\w{5,})(?=\w*\d\d+)/; // Change this line 488 | // freeCodeCamp solution 489 | // var pwRegex = /^\D(?=\w{5})(?=\w*\d{2})/; 490 | // let result = pwRegex.test(sampleWord); 491 | 492 | // console.log(result) 493 | 494 | //////////////////////////////////////////////////////////////////////////////////////// 495 | // Regular Expressions: Check For Mixed Grouping of Characters 496 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/check-for-mixed-grouping-of-characters 497 | 498 | // let testStr = "Pumpkin"; 499 | // let testRegex = /P(engu|umpk)in/; 500 | // testRegex.test(testStr); 501 | // // Returns true 502 | 503 | // Fix the regex so that it checks for the names of Franklin Roosevelt or Eleanor Roosevelt in a case sensitive manner and it should make concessions for middle names. 504 | 505 | // Then fix the code so that the regex that you have created is checked against myString and either true or false is returned depending on whether the regex matches. 506 | 507 | // let myStringPrez = "Eleanor Roosevelt"; 508 | // let myRegexPrez = /(Franklin|Eleanor)(\D*)Roosevelt/; // Change this line 509 | // let resultPrez = myRegexPrez.test(myStringPrez); // Change this line 510 | // console.log(resultPrez); 511 | // After passing the challenge experiment with myString and see how the grouping works 512 | 513 | 514 | //////////////////////////////////////////////////////////////////////////////////////// 515 | // Regular Expressions: Reuse Patterns Using Capture Groups 516 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups 517 | 518 | // let repeatStr = "regex regex"; 519 | // let repeatRegex = /(\w+)\s\1/; 520 | // repeatRegex.test(repeatStr); // Returns true 521 | // repeatStr.match(repeatRegex); // Returns ["regex regex", "regex"] 522 | 523 | // Using the .match() method on a string will return an array with the string it matches, along with its capture group. 524 | 525 | // Use capture groups in reRegex to match numbers that are repeated only three times in a string, each separated by a space. 526 | 527 | // let repeatNum = "42 42 42"; 528 | // let reRegex = /^(\d+\s*)/; // Change this line 529 | // // freeCodeCamp answer 530 | // let reRegexfCC = /^(\d+)\s\1\s\1$/; 531 | // let result = reRegex.test(repeatNum); 532 | // console.log(result); 533 | // console.log(reRegexfCC.test(repeatNum)); 534 | // console.log(repeatNum.match(reRegexfCC)); 535 | 536 | //////////////////////////////////////////////////////////////////////////////////////// 537 | // Regular Expressions: Use Capture Groups to Search and Replace 538 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace 539 | 540 | // let wrongText = "The sky is silver."; 541 | // let silverRegex = /silver/; 542 | // wrongText.replace(silverRegex, "blue"); 543 | // // Returns "The sky is blue." 544 | 545 | // "Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1'); 546 | // // Returns "Camp Code" 547 | 548 | // Write a regex fixRegex using three capture groups that will search for each word in the string "one two three". Then update the replaceText variable to replace "one two three" with the string "three two one" and assign the result to the result variable. Make sure you are utilizing capture groups in the replacement string using the dollar sign ($) syntax. 549 | 550 | // let str = "one two three"; 551 | // let fixRegex = /(\w+)\s(\w+)\s(\w+)/; // Change this line 552 | // let replaceText = "$3 $2 $1"; // Change this line 553 | // let result = str.replace(fixRegex, replaceText); 554 | // console.log(result); 555 | 556 | //////////////////////////////////////////////////////////////////////////////////////// 557 | // Regular Expressions: Remove Whitespace from Start and End 558 | // https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end 559 | 560 | // Write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings. 561 | 562 | // Note: The String.prototype.trim() method would work here, but you'll need to complete this challenge using regular expressions. 563 | 564 | let hello = " Hello, World! "; 565 | let wsRegex = /(\s\s+)/g; // Change this line 566 | let result = hello.replace(wsRegex, ''); // Change this line 567 | console.log(result); 568 | console.log('Hello, World!') 569 | 570 | //////////////////////////////////////////////////////////////////////////////////////// 571 | --------------------------------------------------------------------------------