diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/AddingProperties.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/AddingProperties.html new file mode 100755 index 0000000000000000000000000000000000000000..168b0b7906f00bfe01ad5a1303f3210f601d2d58 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/AddingProperties.html @@ -0,0 +1,37 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>Adding Properties</title> + </head> + + <body> + <script> + "use strict"; + + let sale = {}; + do { + let item = prompt("Enter name of item you want to buy."); + let numberOfItems = Number(prompt("Enter number of items you want to buy")); + + /* Adding property */ + if (sale[item] === undefined) { // IMPORTANT: Otherwise will remove previous value + sale[item] = numberOfItems; + } else { + sale[item] += numberOfItems; + } + + if (!window.confirm("Do you want to buy another item?")) { + break; + } + } while (true); + + /* Report about bought items */ + let report = "Items bought\n"; + for (let propertyName in sale) { + report += propertyName + "-->" + sale[propertyName] + "\n"; + } + alert(report); + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/Destructuring.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/Destructuring.html new file mode 100755 index 0000000000000000000000000000000000000000..45998804ccc2237115a9dbe03e0522d79125a911 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/Destructuring.html @@ -0,0 +1,64 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Destructuring Example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + /* Destructuring arrays */ + let names = ["Andrew", "Karl", "Olivia"]; + let [first, second] = names; + document.writeln("Original Array: " + names + "<br>"); + document.writeln("First: " + first + "<br>" + "Second: " + second + "<br><br>"); + + document.writeln("***** Destructuring Object *****<br>"); + /* Destructuring object */ + let app = { + name: "mapApp", + developed: 1986, + location: "CP" + }; + /* You must use the same property name; try name2 instead of name + You don't need to retrieve all properties (convenient for objects + with several properties) + */ + let { + name, + developed + } = app; /* Notice using { } */ + document.writeln("Name: " + name + ", " + "Developed: " + developed + "<br><br>"); + + document.writeln("***** Destructuring Object in Function Call *****<br>"); + myFunc(app); /* function call */ + function myFunc({developed}){ + document.writeln("In Function: developed: " + developed + "<br><br>"); + } + + document.writeln("***** Destructuring Object in Function Call *****<br>"); + /* function call */ + myFunc2(app); + + /* Using a property name different than original */ + function myFunc2({name: yourName}){ + document.writeln("YourName: " + yourName + "<br><br>"); + } + + document.writeln("***** Swapping Values *****<br>"); + /* swap */ + let a = 100, + b = 200; + [b, a] = [a, b]; + document.writeln(a + ", " + b + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/AsyncAwait.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/AsyncAwait.html new file mode 100755 index 0000000000000000000000000000000000000000..2415ec6fa0bc33e1392754469485069e649b94e6 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/AsyncAwait.html @@ -0,0 +1,30 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + + process(); + + async function process() { + let url = "https://jsonplaceholder.typicode.com/todos/1"; // Notice the 1 at the end + alert(`Retrieving data from ${url} (check console for results)`); + + const response = await fetch(url); + console.log("Response"); + console.log(response); + + const json = await response.json(); + console.log("Json"); + console.log(json); + console.log("***** END OF SCRIPT *****"); // Check WHERE this message appears in the console + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/Cors.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/Cors.html new file mode 100755 index 0000000000000000000000000000000000000000..dc34b7e5f4103696e84f6bc9ee3fb995533e9d9a --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/Cors.html @@ -0,0 +1,33 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>TAs Info</title> + </head> + + <body> + <h3>CORS</h3> + <p> + Try running this example by first opening this file using Live Server and + then by right-clicking on the file and selecting the Chrome browser. + </p> + <div id="display"></div> + <script> + async function readTAsInfo() { + const filename = "./tas.json"; + const response = await fetch(filename); + const data = await response.json(); + let table = ""; + data.forEach((entry) => { + table += `<tr><td>${entry.name}</td><td>${entry.course}</td></tr>`; + }); + const tableHeadSection = `<table border='1'><tr><th>Name</th><th>Course</th></tr>`; + table = `${tableHeadSection}${table}</table>`; + document.querySelector("#display").innerHTML = table; + } + + readTAsInfo(); + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/DisplayingCats.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/DisplayingCats.html new file mode 100755 index 0000000000000000000000000000000000000000..f09a93b6bf2c010853ee8a5d6421206e6de4e07b --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/DisplayingCats.html @@ -0,0 +1,48 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>Displaying cats</title> + </head> + + <body> + <h1>Cat Images</h1> + + <label>Animation speed in milliseconds <input id="speed" type="text" value="1000"></label><br><br> + <input type="button" value="Start Displaying Cats" onclick="startAnimation()"> + <input type="button" value="Stop Animation" onclick="stopAnimation()"><br><br> + <img id="downloadedImage" src="doesnotexistyet.png" height="300" alt="image"><br> + <div id="display"></div> + + <script> + let animationId, animationStarted = false; + + function downloadCatImage() { + let catImagesUrl = `https://api.thecatapi.com/v1/images/search`; + fetch(catImagesUrl) + .then(response => response.json()) + .then(json => { + const imageUrl = json[0].url; + const img = document.querySelector("#downloadedImage"); + img.src = imageUrl; + document.querySelector("#display").innerHTML = `Source: <a href="${imageUrl}">${imageUrl}</a>`; + }); + } + + function startAnimation() { + if (!animationStarted) { /* Preventing executing setInterval multiple times before stopping animation */ + let intervalInMillisecs = document.querySelector("#speed").value; + animationId = setInterval(downloadCatImage, intervalInMillisecs); + animationStarted = true; + } + } + + function stopAnimation() { + if (animationStarted) { + clearInterval(animationId); + animationStarted = false; + } + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/FetchingImage.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/FetchingImage.html new file mode 100755 index 0000000000000000000000000000000000000000..7b7fddb5e3484fe477ea97c47204077c810492a8 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/FetchingImage.html @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>Fetching Image</title> + </head> + + <body> + <h1>Fetching Random Cat Image</h1> + <input type="button" value="DownloadCatImage" onclick="downloadCatImage()"><br><br> + <img src="toPacifyHTMLValidator" id="downloadedImage" height="300" alt="catImg"><br> + + <script> + function downloadCatImage() { + let catImageUrl = `https://api.thecatapi.com/v1/images/search`; + fetch(catImageUrl) + .then(response => response.json()) + .then(json => { + console.log(json); /* Take a look at the console */ + const imageUrl = json[0].url; + const img = document.querySelector("#downloadedImage"); + img.src = imageUrl; + }); + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch1.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch1.html new file mode 100755 index 0000000000000000000000000000000000000000..716b3e8bd78857ef5b483402a066369d636c3475 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch1.html @@ -0,0 +1,22 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + + let url = "https://jsonplaceholder.typicode.com/todos/1"; // Notice the 1 at the end + alert(`Retrieving data from ${url} (check console for results)`); + + const promise = fetch(url); + console.log(promise); + promise.then(response => {console.log(response); return response.json()}).then(json => console.log(json)); // Process json object by displaying on the console + console.log("***** END OF SCRIPT *****"); // Check WHERE this message appears in the console + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch2.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch2.html new file mode 100755 index 0000000000000000000000000000000000000000..d3d88a883e145cfddde191466659bccfbcac96d4 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch2.html @@ -0,0 +1,21 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + + let url = "https://jsonplaceholder.typicode.com/todos/1"; // Notice the 1 at the end + alert(`Retrieving data from ${url}`); + + fetch(url) // Get data + .then(response => response.text()) // Process response by retrieving text + .then(text => document.writeln(text)); // Displaying text + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch3.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch3.html new file mode 100755 index 0000000000000000000000000000000000000000..fbf34e28d517ab54376662efd648aa9c786f8f49 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch3.html @@ -0,0 +1,26 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + + let url = "https://jsonplaceholder.typicode.com/todos/2"; + alert(`Retrieving data from ${url} (check console for results)`); + + fetch(url).then(response => response.json()).then(json => processObject(json)); + + function processObject({userId, id, title}) { // Notice destructoring + console.log("Data Retrieved\n"); + console.log(`user Id: ${userId}`); + console.log(`id: ${id}`); + console.log(`title: ${title}`); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch4.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch4.html new file mode 100755 index 0000000000000000000000000000000000000000..01e18a491018db79ad652448fe91d0a398493df1 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch4.html @@ -0,0 +1,35 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <script> + let url = "https://jsonplaceholder.typicode.com/todos/1"; // Replace 1 with invalid value to see catch effect + alert(`Retrieving data from ${url} (check console for results)`); + + fetch(url) + .then((response) => { + if (!response.ok) { + throw "Problem downloading"; + } else { + return response.json(); + } + }) + .then((json) => processObject(json)) + .catch((error) => console.log("Reporting error: " + error)); + + function processObject(json) { + console.log("Data Retrieved\n"); + console.log(json); + console.log("Accessing properties\n"); + console.log(`user Id: ${json.userId}`); + // throw "Faking an error took place"; // Uncomment to faking an error; will trigger catch above + console.log(`id: ${json.id}`); + console.log(`title: ${json.title}`); + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch5.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch5.html new file mode 100755 index 0000000000000000000000000000000000000000..0e402634cf7fe2b6f3ddf28cdda8c21cfcd0ccba --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/PromisesFetch5.html @@ -0,0 +1,29 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <title>Example</title> + <meta charset="utf-8"> +</head> + +<body> + <script> + let url = "https://jsonplaceholder.typicode.com/todos/"; // Now retrieving a lot of entries + alert(`Retrieving data from ${url} (check console for results)`); + + fetch(url) + .then(response => response.json()) + .then(arrayOfObjects => printTitles(arrayOfObjects)) + .catch(error => console.log("Reporting error: " + error)); + + function printTitles(arrayOfObjects) { + // Our response is an array of values + console.log("\n\n***** Titles Received *****\n"); + for (let entry of arrayOfObjects) { + console.log(entry.title); + } + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/tas.json b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/tas.json new file mode 100755 index 0000000000000000000000000000000000000000..d69cf6656ba8181ba203c4fb50f13ad75fe7a10f --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/FetchExamples/tas.json @@ -0,0 +1,7 @@ +[ + {"name": "Pete", "course": "CMSC335"}, + {"name": "Rose", "course": "CMSC216"}, + {"name": "Michael", "course": "CMSC335"}, + {"name": "Laura", "course": "CMSC216"}, + {"name": "Kathleen", "course": "CMSC335"} +] \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/JSONExample.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/JSONExample.html new file mode 100755 index 0000000000000000000000000000000000000000..fa17aed44e4b719c288b746ccf10a7c9f4d9ea35 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/JSONExample.html @@ -0,0 +1,57 @@ +<!DOCTYPE html> + +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>JS JSON Example</title> + <style> + h2 {text-decoration: underline} + </style> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + let obj = { + "name": "Mary", + "age": 45, + "salary": 20000.00, + "employed": true, + "boss": null, + "cars": ["toyota", "honda"], /* array example */ + "friends": [{ /* array of objects */ + "fname": "Peter" + }, { + "fname": "Rachel" + }] + }; + document.writeln("<h2>JSON String (After stringify Object)</h2>"); + let str = JSON.stringify(obj); + document.writeln(str); + + + document.writeln("<h2>After Parsing String</h2>") + let newObj = JSON.parse(str); + for (let prop in newObj) { + document.writeln(prop + "→" + newObj[prop] + "<br>"); + } + + + document.writeln("<h2>Check console to see object corresponding to following string</h2>"); + /* Using template literal */ + let secondObjStr = `{ + "school": "UMCP", + "zipCode": 20742 + }`; + document.writeln("String: " + secondObjStr + "<br>"); + let secondObj = JSON.parse(secondObjStr); + console.log(secondObj); + console.table(secondObj); + } + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JSObjectsFetchCode/Objects.html b/LectureCodeExamples/Week1/JSObjectsFetchCode/Objects.html new file mode 100755 index 0000000000000000000000000000000000000000..aedcde63b0add62c0033c106a6fbadb387b19aa7 --- /dev/null +++ b/LectureCodeExamples/Week1/JSObjectsFetchCode/Objects.html @@ -0,0 +1,91 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Objects Example</title> +</head> + +<body> + <script> + main(); + + function main() { + /* Alternatives for creating an empty object */ + let emptyObject1 = new Object(); + let emptyObject2 = new Object(undefined); + let emptyObject3 = new Object(null); + let emptyObject4 = {}; + + /* Boolean Object alternative */ + let booleanObject1 = new Object(true); + let booleanObject2 = new Boolean(true); + + /* Number Object alternative */ + let numObject1 = new Object(3); + let numObject2 = new Number(3); + + /* String Object alternative */ + let strObject1 = new Object("Hello world"); + let strObject2 = new String("Hello world"); + + /* Using Object constructor for person object */ + let person1 = new Object(); + /* Adding properties */ + /* Alternative to next assignment -> person1.name = "John"; */ + person1["name"] = "John"; + person1.age = 45; + person1.school = umcpSchool; + /* Printing person */ + printPerson(person1); + + /* Using object initializer/literal notation */ + let person2 = { + name: "Mary", /* We could have used "name":"Mary" */ + age: 30, /* We could have used "age": 30 */ + school: umcpSchool, /* Assigning a method */ + bestFriend: person1 /* Assigning an object */ + }; + /* Printing person */ + printPerson(person2); + + let exam = { + semester: "fall", + "difficulty-level": 10, /* Needs " " as key is not valid */ + 3: "midterm3", + "": "empty string" + }; + exam[person1] = "person1"; + + /* Printing to console */ + document.writeln("<br>***** Check console for output *****<br>"); + console.log("\n\n ***** Printing exam object *****\n\n"); + console.log(exam); + console.log("\n\n ***** Printing exam object using table *****\n\n"); + console.table(exam); /* Using console.table */ + + console.log(" ***** Creating object copy *****\n"); + let exam2 = Object.create(exam); + exam2['3'] = 'final'; + console.table(exam2); + } + + function printPerson(personParam) { + document.writeln("Name: " + personParam.name + ", "); + document.writeln("Age: " + personParam.age + ", "); + if (personParam.bestFriend != undefined) { + document.writeln( + "Best Friend: " + personParam.bestFriend.name + ", " + ); + } + personParam.school(); + } + + function umcpSchool() { + document.writeln("University of MD College Park" + "<br>"); + } + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/ConsoleEx.html b/LectureCodeExamples/Week1/JavaScriptIICode/ConsoleEx.html new file mode 100755 index 0000000000000000000000000000000000000000..3e36b068f52d84922aadf984e2d40ea936cdeb56 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/ConsoleEx.html @@ -0,0 +1,28 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Example</title> +</head> + +<body> + <script> + let option = prompt("Enter error, info, warn or log"); + + if (option === "error") { + console.error("Using console.error"); + } else if (option === "info") { + console.info("Using console.info"); + } else if (option === "warn") { + console.warn("Using console.warn"); + } else if (option === "log") { + console.log("Using console.log"); + } else { + console.log("Invalid option: " + option); + } + + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/DefiningFunctions.html b/LectureCodeExamples/Week1/JavaScriptIICode/DefiningFunctions.html new file mode 100755 index 0000000000000000000000000000000000000000..2aad00117e7d3c76427b5552ccf636cf400df73b --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/DefiningFunctions.html @@ -0,0 +1,31 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>JS Example</title> + </head> + + <body> + <script> + document.writeln( + "Before function declaration: " + product(3, 4) + "<br>" + ); + + /* Function declaration */ + function product(x, y) { + return x * y; + } + document.writeln("Function declaration: " + product(3, 4) + "<br>"); + + /* Function expression (anonymous function) */ + let productTwo = function (x, y) { + return x * y; + }; + document.writeln("Function expression: " + productTwo(100, 200) + "<br>"); + + /* Using Function constructor */ + let productThree = new Function("x", "y", "return x * y"); + document.writeln("Function constructor: " + productThree(2, 3)); + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/DisplayValues.html b/LectureCodeExamples/Week1/JavaScriptIICode/DisplayValues.html new file mode 100755 index 0000000000000000000000000000000000000000..040cb0bbdcaecfda9fb8b7dcf06db88260134ed8 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/DisplayValues.html @@ -0,0 +1,50 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>Process Values</title> + </head> + + <body> + <script> + "use strict"; + + main(); + + function main() { + let numberOfValues = Number(prompt("Enter number of values to print")); + /* We don't need to use window window.confirm */ + let wantHTML = window.confirm( + "Press OK for formatted output and Cancel otherwise" + ); + let printingFunction; + + if (wantHTML) { + printingFunction = htmlFormatFunction; + } else { + printingFunction = textFormatFunction; + } + + displayValues(numberOfValues, printingFunction); + } + + function textFormatFunction(data) { + document.writeln(data); + } + + function htmlFormatFunction(data) { + let output = "<span style='color:red;font-size:4em'><strong>"; + + output += data + " </strong></span>"; + document.writeln(output); + } + + function displayValues(maximum, printFunction) { + for (let curr = 1; curr < maximum; curr++) { + printFunction(curr); + } + printFunction(maximum); + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/FunctionsAsData.html b/LectureCodeExamples/Week1/JavaScriptIICode/FunctionsAsData.html new file mode 100755 index 0000000000000000000000000000000000000000..f533abe617655097c6a63299128872495265a237 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/FunctionsAsData.html @@ -0,0 +1,28 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>Functions as Data</title> + </head> + + <body> + <script> + "use strict"; + + /* We don't need to have a main function */ + main(); + + function main() { + const sayHi = hello; + const hi = hello; + hi("John"); + hello("John"); + sayHi("John"); + } + + function hello(name) { + document.writeln("Hello " + name + "<br>"); + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/GlobalObject.html b/LectureCodeExamples/Week1/JavaScriptIICode/GlobalObject.html new file mode 100755 index 0000000000000000000000000000000000000000..d5239999cb611b26c3822bf133f2bd9ec84ef12a --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/GlobalObject.html @@ -0,0 +1,41 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JavaScript Program Template</title> +</head> + +<body> + john + peter + <script> + "use strict"; + + console.log("window contents"); + console.log(window); + + console.log("globalThis contents"); + console.log(globalThis); + + let message; + if (window === globalThis) { + message = "the same"; + } else { + message = "they are not the same"; + } + + document.writeln(message, "<br>"); + let finalMessage = message + "<br>" + "Done"; + alert(finalMessage); + + var value = 10; + console.log("window.value is: " + window.value); + + let secondValue = 10; + console.log("window.secondValue is: " + window.secondValue); + document.writeln("Output available in the console"); + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/InputOutput.html b/LectureCodeExamples/Week1/JavaScriptIICode/InputOutput.html new file mode 100755 index 0000000000000000000000000000000000000000..6cea89209835a86e1febb63103c1d43a61436e7e --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/InputOutput.html @@ -0,0 +1,29 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>Input/Output</title> +</head> + +<body> + <script> + "use strict"; + + document.writeln("<strong>" + "Bill Calculation System</strong><br />"); + + let costPerCredit, numberOfCredits, tuitionCost; + + /* Reading values from the user */ + costPerCredit = Number(prompt("Enter cost per credit:")); + numberOfCredits = prompt("Enter number of credits:", 15); + + /* Computing cost */ + tuitionCost = costPerCredit * numberOfCredits; + + document.writeln("<strong>Tuition Cost: </strong>" + tuitionCost); + </script> +</body> + +</html> + diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/Network.html b/LectureCodeExamples/Week1/JavaScriptIICode/Network.html new file mode 100755 index 0000000000000000000000000000000000000000..5ba82768cb4ff9600ae6b1f346e2b411c73cbe89 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/Network.html @@ -0,0 +1,34 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>Network</title> +</head> + +<body> + <script> + "use strict"; + + /* You need to allow browser pop-ups to run this program */ + let network = prompt("Enter network name (abc, cbs)"); + alert("Network specified is: " + network); + let webSite; + + switch (network) { + case "abc": + webSite = "http://www.abc.com/"; + break; + case "cbs": + webSite = "http://www.cbs.com/"; + break; + default: + webSite = "http://www.cnn.com/"; + break; + } + window.open(webSite); + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/SqrTable.html b/LectureCodeExamples/Week1/JavaScriptIICode/SqrTable.html new file mode 100755 index 0000000000000000000000000000000000000000..ebc358813742d66c18f1910df07c93f95b2130d7 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/SqrTable.html @@ -0,0 +1,42 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>Square Root Table</title> +</head> + +<body> + <script> + "use strict"; + + let currValue = 0, + maximumValue; + + /* Reading a value from the user and verifying is correct */ + do { + maximumValue = Number(prompt("Enter a value")); + if (maximumValue < 0) { + alert("Invalid value: " + maximumValue); + } + } while (maximumValue < 0); + + /* Generating the table */ + /* document.writeln writes a string of text followed by a newline */ + /* character to a document. Try also document.write(...) */ + document.writeln("<table border=\"2\">"); + document.writeln("<caption><strong>Square Root Table</strong></caption>"); + document.writeln("<tr><th>Number</th><th>Square Root</th></tr>"); + + while (currValue <= maximumValue) { + document.writeln("<tr><td>" + currValue + "</td><td>"); + document.writeln(Math.sqrt(currValue) + "</td></tr>"); + currValue = currValue + 1; + } + + document.writeln("</table>"); + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/Strict.html b/LectureCodeExamples/Week1/JavaScriptIICode/Strict.html new file mode 100755 index 0000000000000000000000000000000000000000..def7aa76c3d8a2f4dcd1cac2a78027be46514156 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/Strict.html @@ -0,0 +1,21 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>Strict Example</title> +</head> + +<body> + <script> + // Inspect the console for each case below + 'use strict'; + + /* strict mode requires variable to be declared first */ + bookTitle = "Introduction to JavaScript"; + document.writeln(bookTitle); + + /* Following variable name not allowed in strict mode */ + // let interface = 10; + + </script> +</body></html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/Wrapper.html b/LectureCodeExamples/Week1/JavaScriptIICode/Wrapper.html new file mode 100755 index 0000000000000000000000000000000000000000..1c30e677ec46702a34f0d64d62111d6e58ea9ac9 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/Wrapper.html @@ -0,0 +1,28 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>charAt Example</title> +</head> + +<body> + <script> + "use strict"; + + let name = "Testudo"; + let letter = name.charAt(1); /* Autoboxing takes place */ + document.writeln("Letter is " + letter + "<br>"); + + /* JavaScript engine processing for above code */ + name = "Testudo"; + let x = new String(name); + letter = x.charAt(1); + x = null; /* x will be destroyed once is no longer needed */ + + document.writeln("Letter is " + letter); + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/WrapperType.html b/LectureCodeExamples/Week1/JavaScriptIICode/WrapperType.html new file mode 100755 index 0000000000000000000000000000000000000000..8707a392f47881ee9f01dcb53d20c9963879e232 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/WrapperType.html @@ -0,0 +1,31 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>Wrapper object type example</title> +</head> + +<body> + <script> + "use strict"; + + function comparison(test, x, y) { + let answer = ""; + + answer += "Test: " + test + "<br>"; + answer += "type of x " + typeof x + "<br>"; + answer += "type of y " + typeof y + "<br>"; + answer += "x == y → " + (x == y) + "<br>"; + answer += "x === y → " + (x === y) + "<br>"; + answer += "x.localeCompare(y) → " + x.localeCompare(y) + "<br><br>"; + document.writeln(answer); + } + comparison("test1", "Testudo", new String("Testudo")); + comparison("test2", "Testudo", String("Testudo")); + comparison("test3", String("Testudo"), new String("Testudo")); + comparison("test4", new String("Testudo"), new String("Testudo")); + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIICode/WriteVsWriteln.html b/LectureCodeExamples/Week1/JavaScriptIICode/WriteVsWriteln.html new file mode 100755 index 0000000000000000000000000000000000000000..4dfd266757853d23d626c5bb123ce1b9a3e95d09 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIICode/WriteVsWriteln.html @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>charAt Example</title> +</head> + +<body> + <script> + "use strict"; + + document.write("<h2>Using write for text</h2>"); + document.write("<pre>"); + document.write("The house is blue"); + document.write(" and near our place"); + document.write("</pre>"); + + document.write("<h2>Using writeln for text</h2>"); + document.write("<pre>"); + document.writeln("The house is blue"); + document.writeln(" and near our place"); + document.write("</pre>"); + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/ArrayMethods.html b/LectureCodeExamples/Week1/JavaScriptIIICode/ArrayMethods.html new file mode 100755 index 0000000000000000000000000000000000000000..40debe0e528c96de16b5d2e404b2df30c09600ea --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/ArrayMethods.html @@ -0,0 +1,101 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>Array Methods</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function printArray(data) { + var i; + + for (i = 0; i < data.length; i++) { + document.writeln(data[i] + " "); + } + document.writeln("<br>"); + } + + function main() { + document.writeln("***** Creating Array *****<br>"); + let languages = ["JavaScript", "Java", "PHP", "Python"]; + document.writeln("Array of Languages: " + languages + "<br>") + document.writeln("Length: " + languages.length + "<br><br>"); + + + document.writeln("***** After pushing C *****<br>"); + languages.push("C"); + document.writeln("Languages: " + languages.join() + "<br><br>"); /* Using join() */ + + + document.writeln("***** After pop *****<br>"); + let popped = languages.pop(); + document.writeln("Popped element: " + popped + "<br>"); + document.writeln("Languages: " + languages.join("*") + "<br><br>"); /* Using join() */ + + + document.writeln("***** After shift *****<br>"); + let shiftedElement = languages.shift(); + document.writeln("Shifted element: " + shiftedElement + "<br>"); + document.writeln("Languages: " + languages.join("---") + "<br><br>"); /* Using join() */ + + + document.writeln("***** After unshift *****<br>"); + languages.unshift(shiftedElement); + document.writeln("Languages: " + languages.join(",") + "<br><br>"); + + + document.writeln("***** Finding index of Python *****<br>"); + document.writeln("Languages: " + languages.join(",") + "<br>"); + document.writeln("Index: " + languages.indexOf("Python") + "<br><br>"); + + + document.writeln("***** Using splice *****<br>"); + languages = ["JavaScript", "Java", "PHP", "Python", "Ruby", "C#"]; + document.writeln("Languages: " + languages.join(",") + "<br>"); + let start = 1, end = 3; + document.writeln("Using arguments " + start + ", " + end + "<br>"); + let returnedValue = languages.splice(start, end); + document.writeln("Languages array after splice: " + languages.join(",") + "<br>"); + document.writeln("Value returned by splice: " + returnedValue.join(",") + "<br><br>"); + + + document.writeln("***** Using slice *****<br>"); + languages = ["JavaScript", "Java", "PHP", "Python", "Ruby", "C#"]; + document.writeln("Languages: " + languages.join(",") + "<br>"); + start = 1, end = 3; + document.writeln("Using arguments " + start + ", " + end + "<br>"); + returnedValue = languages.slice(start, end); + document.writeln("Languages array after slice: " + languages.join(",") + "<br>"); + document.writeln("Value returned by slice: " + returnedValue.join(",") + "<br><br>"); + + + document.writeln("***** Using reverse *****<br>"); + let seasons = ["Fall", "Winter", "Spring", "Summer"]; + document.writeln("Seasons: " + seasons.join(",") + "<br>"); + seasons.reverse(); + document.writeln("After reversing seasons array: " + seasons.join(", ") + "<br><br>"); + + + document.writeln("***** Using concat *****<br>"); + let part1 = [10, 20, 30], part2 = [40, 60]; + document.writeln("Concatenating: " + part1.join() + " and " + part2.join() + "<br>"); + let combined = part1.concat(part2); + document.writeln("Concatenating result: " + combined + "<br><br>"); + + + document.writeln("***** Using fill *****<br>"); + document.writeln("Filling array with value 100<br>"); + let filled = new Array(4).fill(100); + document.writeln("Result: " + filled + "<br><br>"); + } + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/ArraySlice.html b/LectureCodeExamples/Week1/JavaScriptIIICode/ArraySlice.html new file mode 100755 index 0000000000000000000000000000000000000000..9b01e12589e2ef97aa016f4e1bfccf87af58c19c --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/ArraySlice.html @@ -0,0 +1,44 @@ +<!doctype html> +<html lang="en"> + +<head> + <meta charset="utf-8" /> + <title>Array Slice Example</title> +</head> + +<body> + <script> + "use strict"; + + let arr = new Array(); + arr.push({ + name: 'Maryland' + }); + arr.push({ + name: 'Virginia' + }); + arr.push({ + name: 'Delaware' + }); + + document.writeln("<strong>Check console for array information</strong><br>"); + console.log("\n\nOriginal array"); + console.table(arr); /* Notice the use of console.table() */ + let sliced = arr.slice(1, 3); /* Only VA and DE */ + console.log("\n\nResult of slice 1, 3"); + console.table(sliced); + + /* Modifying entry of sliced */ + sliced[0].name = 'Texas'; + + console.log("\n\nPrinting original and sliced array after "); + console.log("modification (Texas) (shows shallow copy)"); + console.log("\n\nOriginal array"); + console.table(arr); + console.log("\n\nsliced array"); + console.table(sliced); + + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/ArraysLengthProp.html b/LectureCodeExamples/Week1/JavaScriptIIICode/ArraysLengthProp.html new file mode 100755 index 0000000000000000000000000000000000000000..2b8e440cd63a370124eb17cf75f1860db08009c4 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/ArraysLengthProp.html @@ -0,0 +1,48 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8"> + <title>Arrays Length Property</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + let languages = ["English", "Spanish", "French"]; + + document.writeln("Array: "); + printArray(languages); + document.writeln("Length: " + languages.length + "<br><br>"); + + /* See what values are used for the elements in the middle */ + languages[8] = "Italian"; + document.writeln("After adding Italian<br>"); + printArray(languages); + + /* The Object.keys() method returns an array of a given + object's own enumerable property names, in the same order as + we get with a normal loop. */ + let keys = Object.keys(languages); + document.writeln("<br>Keys: " + keys + "<br>"); + document.writeln("Keys length: " + keys.length + "<br>"); + document.writeln("Languages length: " + languages.length + "<br>"); + + languages.length = 2; + document.writeln("<br>After changing length<br>"); + printArray(languages); + + } + + function printArray(data) { + for (let i = 0; i < data.length; i++) { + document.writeln(data[i] + " "); + } + document.writeln("<br>"); + } + </script> +</body></html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/ArraysOneDim.html b/LectureCodeExamples/Week1/JavaScriptIIICode/ArraysOneDim.html new file mode 100755 index 0000000000000000000000000000000000000000..3456a36d9af5c4a9061e89e87fcf85d153146239 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/ArraysOneDim.html @@ -0,0 +1,46 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>Arrays</title> + </head> + + <body> + <script> + "use strict"; + main(); + + function main() { + let numOfBeds = 4; + + let roomNumber = reserveRoom(numOfBeds); + printRoom(roomNumber); + + cleanRoom(roomNumber); + printRoom(roomNumber); + } + + function reserveRoom(numberOfBeds) { + let roomNumber = new Array(numberOfBeds); + + for (let idx = 0; idx < roomNumber.length; idx++) { + roomNumber[idx] = "Bed" + idx; + } + + return roomNumber; + } + + function printRoom(roomNumberParameter) { + for (let idx = 0; idx < roomNumberParameter.length; idx++) { + document.writeln(roomNumberParameter[idx] + "<br>"); + } + } + + function cleanRoom(roomNumberParameter) { + for (let idx = 0; idx < roomNumberParameter.length; idx++) { + roomNumberParameter[idx] += " cleaned "; + } + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/ArraysTwoDim.html b/LectureCodeExamples/Week1/JavaScriptIIICode/ArraysTwoDim.html new file mode 100755 index 0000000000000000000000000000000000000000..90c4f6c5d7e521c598ff532d72918b8f7693d366 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/ArraysTwoDim.html @@ -0,0 +1,67 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>Two-Dimensional Arrays</title> + </head> + + <body> + <script> + "use strict"; + main(); + + function main() { + document.writeln("<h2>First Data Set</h2>"); + const firstArray = [ + [10, 20, 30], + [40, 50, 60], + [70, 80, 90], + ]; + printArray(firstArray); + + document.writeln("<h2>Second Data Set</h2>"); + let secondArray = createArray(2, 3); + initializeArray(secondArray, 1); + printArray(secondArray); + + document.writeln("<h2>Third Data Set (Ragged Array)</h2>"); + const thirdArray = [ + [100, 200, 300], + [400], + [700, 800], + [], + [500, 600, 900, 1000], + ]; + printArray(thirdArray); + } + + function createArray(maxRows, maxCols) { + let newArray = new Array(maxRows); + + for (let row = 0; row < maxRows; row++) { + newArray[row] = new Array(maxCols); + } + + return newArray; + } + + function initializeArray(data, initialValue) { + for (let row = 0; row < data.length; row++) { + for (let col = 0; col < data[row].length; col++) { + data[row][col] = initialValue; + initialValue++; + } + } + } + + function printArray(data) { + for (let row = 0; row < data.length; row++) { + for (let col = 0; col < data[row].length; col++) { + document.writeln(data[row][col] + " "); + } + document.writeln("<br>"); + } + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/CharAt.html b/LectureCodeExamples/Week1/JavaScriptIIICode/CharAt.html new file mode 100755 index 0000000000000000000000000000000000000000..4fd7b97f904461e91589d57d167d0cef430bebfe --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/CharAt.html @@ -0,0 +1,52 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>charAt Example</title> + </head> + + <body> + <script> + "use strict"; + + main(); + + function main() { + let value = prompt("Enter four digit value"), + message; + + if (validDigits(value, 4)) { + message = "Correct value provided"; + } else { + message = "Incorrect value provided"; + } + alert(message); + } + + function findInstancesOfChar(str, target) { + let count = 0; + + for (let idx = 0; idx < str.length; idx++) { + if (str[idx] === target) { + count++; + } + } + + return count; + } + + function validDigits(data, length) { + if (data.length !== length) { + return false; + } else { + for (let idx = 0; idx < data.length; idx++) { + if (isNaN(data.charAt(idx))) { + return false; + } + } + return true; + } + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/ErrorHandler.js b/LectureCodeExamples/Week1/JavaScriptIIICode/ErrorHandler.js new file mode 100755 index 0000000000000000000000000000000000000000..61d86aab4f502621ec12a5d24f337a8b285877b5 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/ErrorHandler.js @@ -0,0 +1,12 @@ + +window.onerror = handleErr; + +function handleErr(msg, url, line) { + let message = "Error: " + msg + "\n"; + + message += "URL: " + url + "\n"; + message += "Line Number: " + line; + alert(message); + + return true; +} diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/ErrorHandlerEx.html b/LectureCodeExamples/Week1/JavaScriptIIICode/ErrorHandlerEx.html new file mode 100755 index 0000000000000000000000000000000000000000..d1dc6ed37869fba10b7abbff68d1a94fae7fc6b7 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/ErrorHandlerEx.html @@ -0,0 +1,23 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>Error Handler Example</title> + + <!-- Add the following line to your code and put the ErrorHandler.js file + in the same folder your program is --> + + <script src="ErrorHandler.js"></script> + </head> + + <body> + <h1>Adding Error Checking Via Error Handler</h1> + + <script> + let value; + + value = 100; // Remove the = and see what happens + document.writeln("Test Value used is: " + value); + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/ForIn.html b/LectureCodeExamples/Week1/JavaScriptIIICode/ForIn.html new file mode 100755 index 0000000000000000000000000000000000000000..4f65282a2247da08d38873d3f659d9cc0a77f6e9 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/ForIn.html @@ -0,0 +1,32 @@ +<!doctype html> +<html lang="en"> + +<head> + <meta charset="utf-8" /> + <title>for</title> +</head> + +<body> + <script> + "use strict"; + + let employee = { + name: "Mary", + age: 15, + newEmployee: true + }; + + document.writeln("Employee<br>"); + for (let key in employee) { + document.writeln(key + ": " + employee[key] + "<br>"); + } + + document.writeln("<br>Scores<br>"); + let scores = [10, 20, 30]; + for (let key in scores) { + document.writeln(key + ": " + scores[key] + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/ForOf.html b/LectureCodeExamples/Week1/JavaScriptIIICode/ForOf.html new file mode 100755 index 0000000000000000000000000000000000000000..489a7414f9462a627f8125aa10af3275736a2e92 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/ForOf.html @@ -0,0 +1,28 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>for</title> +</head> + +<body> + <script> + "use strict"; + + document.writeln("***** Iterating Over Array *****<br>"); + let languages = ["C++", "Fortran", "JavaScript"]; + for (let lang of languages) { + document.writeln(lang + "<br>"); + } + document.writeln("<br>"); + + document.writeln("***** Iterating Over String *****<br>"); + let name = "Michael"; + for (let letter of name) { + document.writeln(letter + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/NaN.html b/LectureCodeExamples/Week1/JavaScriptIIICode/NaN.html new file mode 100755 index 0000000000000000000000000000000000000000..6b5edf3373a1efe0875b40e25b4738a6113015ed --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/NaN.html @@ -0,0 +1,55 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>NaN example</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + let examScore = 84.5, + name = "Mary Smith", message = ""; + + message += "examScore is a not number: " + isNaN(examScore) + "<br>"; + message += "window.isNaN(NaN): " + window.isNaN(NaN) + "<br>"; + message += "Number.isNaN(NaN): " + Number.isNaN(NaN) + "<br>"; + message += "empty string to number: " + Number("") + "<br>"; + message += "string to number: " + Number(name) + "<br><br>"; + + + message += "empty string is not a number: " + window.isNaN("") + "<br>"; + message += "empty string is not a number: " + Number.isNaN("") + "<br><br>"; + + + message += `"${name}" is not a number: ` + window.isNaN(name) + "<br>"; + message += `"${name}" is not a number: ` + Number.isNaN(name) + "<br><br>"; + + message += "NaN == NaN: " + (NaN == NaN) + "<br>"; + message += "NaN === NaN: " + (NaN === NaN) + "<br><br>"; + + + message += "\"-24\" is a number: " + !isNaN("-24") + "<br>"; + message += "\"+24\" is a number: " + !isNaN("+24") + "<br>"; + message += "parseInt(\"24Hi\"): " + parseInt("24Hi") + "<br>"; + message += "parseFloat(\"55.78Hi\"): " + parseFloat("55.78Hi") + "<br>"; + message += "parseInt(\"Hi\"): " + parseInt("Hi") + "<br><br>"; + + + message += "Number(\"24Hi\"): " + Number("24Hi") + "<br>"; + message += "\"24Hi\" is a number: " + !window.isNaN("24Hi") + "<br>"; + message += "\"24Hi\" is a number: " + !Number.isNaN("24Hi") + "<br>"; + + + + document.writeln(message); + } + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/Sorting.html b/LectureCodeExamples/Week1/JavaScriptIIICode/Sorting.html new file mode 100755 index 0000000000000000000000000000000000000000..13d98c9c910a98e551ad97653ab407ee783d5c1b --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/Sorting.html @@ -0,0 +1,93 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>Sorting</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + document.writeln("***** Strings sorting *****<br>"); + let names = ["Rose", "Bob", "Tom", "Albert"]; + document.writeln("Original array: " + names.join() + "<br>"); + names.sort(); /* Sorting */ + document.writeln("After sorting array: " + names.join() + "<br><br>"); + + document.writeln("***** Numerical sorting (unicode code point order generates "); + document.writeln("unexpected result) *****<br>"); + let scores = [30, 2, 4, 5]; + document.writeln("Original array: " + scores.join() + "<br>"); + scores.sort(); /* Sorting */ + document.writeln("Wrong sort: " + scores.join() + "<br><br>"); + + document.writeln("***** Numerical sorting (using comparison function) *****<br>"); + scores.sort(function(x, y) { + return x - y; + }); + document.writeln("After sorting: " + scores.join() + "<br><br>"); + + + document.writeln("***** Sorted names in descending order *****<br>"); + names.sort(strCompareDescending); + document.writeln(names.join() + "<br><br>"); + + document.writeln("***** Sorting array of objects (students) by name *****<br>"); + document.writeln("See console for results"); + let students = [{ + name: "John", + id: 3 + }, + { + name: "Peter", + id: 2 + }, + { + name: "Mary", + id: 10 + } + ]; + + students.sort(function(x, y) { + return x.name.localeCompare(y.name); // or return strCompare(x.name, y.name); + }); + + console.log("\n\nResult of sorting students by name"); + console.table(students); + + document.writeln("<br><br>Using sort to randomize an array (reload the page several times)<br>"); + let data = [2, 3, 4, 5]; + document.writeln("Original array: " + data.join() + "<br>"); + data.sort((x, y) => Math.random() - 0.5); + document.writeln("Randomized array: " + data.join()); + } + + function strCompareDescending(x, y) { + if (x < y) { + return 1; + } else if (x > y) { + return -1; + } else { + return 0; + } + } + + function strCompare(x, y) { + if (x < y) { + return -1; + } else if (x > y) { + return 1; + } else { + return 0; + } + } + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/StringMethods.html b/LectureCodeExamples/Week1/JavaScriptIIICode/StringMethods.html new file mode 100755 index 0000000000000000000000000000000000000000..91c8a7c0bdbee9fe6c2380715b480948ac89a21d --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/StringMethods.html @@ -0,0 +1,81 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>String Methods</title> + </head> + + <body> + <script> + "use strict"; + + main(); + + function main() { + let str1 = prompt("Enter string value", "the roadmap"); + let str2 = prompt("Enter string value", "map"), result; + + /* string comparison */ + if (str1 <= str2) { + document.writeln(str1 + " <= " + str2); + } else if (str1 > str2) { + document.writeln(str1 + " > " + str2); + } else { + document.writeln("str1 equal to str2"); + } + + if (str1.includes(str2)) { + document.writeln("<br>" + str1 + " includes " + str2); + } else { + document.writeln("<br>" + str1 + " does not include " + str2); + } + + if (str1.startsWith("the")) { + document.writeln("<br>" + str1 + ' starts with "the"'); + } else { + document.writeln("<br>" + str1 + ' does not start with "the"'); + } + + if (str1.endsWith("ing")) { + document.writeln("<br>" + str1 + ' ends with "ing"'); + } else { + document.writeln("<br>" + str1 + ' does not end with "ing"'); + } + + document.writeln( + '<br>"Fear the turtle".indexOf("the")→' + + "Fear the turtle".indexOf("the") + ); + document.writeln( + '<br>"Fear the turtle".indexOf("boat")→' + + "Fear the turtle".indexOf("boat") + ); + document.writeln( + '<br>"Fear the turtle".indexOf("")→' + + "Fear the turtle".indexOf("") + ); + document.writeln( + '<br>"Fear the turtle".lastIndexOf("e")→' + + "Fear the turtle".lastIndexOf("e") + ); + + document.writeln("<br>" + str1 + ".repeat(3)→" + str1.repeat(3)); + document.writeln( + "<br>" + '"Feartheturtle".slice(2, 7) ' + "Feartheturtle".slice(2, 7) + ); + document.writeln( + "<br>" + '"Feartheturtle".slice(-7) ' + "Feartheturtle".slice(-7) + ); + + str1 = prompt("Enter comma separated string", "10, 5, 67"); + let strArray = str1.split(","); + document.writeln("<br>Comma Separated String Elements:<br>"); + for (let i = 0; i < strArray.length; i++) { + document.writeln( + strArray[i] + "* Length: " + strArray[i].length + "<br>" + ); + } + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIIICode/TemplateLiteral.html b/LectureCodeExamples/Week1/JavaScriptIIICode/TemplateLiteral.html new file mode 100755 index 0000000000000000000000000000000000000000..929e271fb16566cf985caf07adca372df170a0f6 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIIICode/TemplateLiteral.html @@ -0,0 +1,59 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>JS Example</title> + </head> + + <body> + <script> + "use strict"; + + main(); + + function getLetter(name, body, signature) { + let letter = `<br>Dear ${name}: + <br> + <br> + ${body} + <br> + <br> + Sincerely + <br><br><br> + ${signature}<hr>`; + alert(letter); + return letter; + } + + function sum(x, y) { + return x + y; + } + + function main() { + document.writeln("***** Interpolating Variable *****<br>"); + let mascot = "turtle"; + let message = `Fear the ${mascot}`; + document.writeln(message + "<br><br>"); + + document.writeln("<br>***** Generating Letter *****<br>"); + document.writeln(getLetter("Mary", "How are you doing?", "Peter")); + + document.writeln("***** Interpolating Expression *****<br>"); + let x = 20,y = 30; + let totalCost = `<br>Total Cost is ${x * y}`; + document.writeln(totalCost); + + document.writeln("***** Interpolating Function Call *****<br>"); + let sumResult = `<br>Sum is ${sum(x, y)}`; + document.writeln(sumResult); + + document.writeln("<br><br>***** Space in Template Literals Matters *****<br>"); + const string = `Hello + + terps!`; + + document.writeln("<pre>" + string + "</pre>"); + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIVCode/BlockScope.html b/LectureCodeExamples/Week1/JavaScriptIVCode/BlockScope.html new file mode 100755 index 0000000000000000000000000000000000000000..fffdf4ede81b2ca6d5a4d1131e8dba3e96dd5fb6 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIVCode/BlockScope.html @@ -0,0 +1,52 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>Block Scope</title> +</head> + +<body> + <script> + "use strict"; + + /* Try each of the following function calls */ + document.writeln("<h2>Testing var and let</h2>"); + // usingVar(); + // usingLet(); + // let answer = evaluateVar(200); document.writeln("|Answer is: " + answer +"<br>"); + // let answer = evaluateLet(200); document.writeln("|Answer is: " + answer +"<br>"); + + function usingVar() { + for (var i = 1; i <= 4; i++) { + document.writeln(i + " "); + } + document.writeln("<br>value of i outside loop: " + i + "<br>"); + } + + function usingLet() { + for (let i = 1; i <= 4; i++) { + document.writeln(i + " "); + } + document.writeln("<br>Check console result"); + document.writeln("<br>value of i outside loop: " + i + "<br>"); + } + + function evaluateVar(x) { + if (x >= 100) { + var y = x * 100; + document.writeln("Value in if: " + y); + } + return y; + } + + function evaluateLet(x) { + if (x >= 100) { + let y = x * 100; + document.writeln("Value in if: " + y); + } + document.writeln("<br>Check console result"); + return y; // Generates ReferenceError + } + </script> +</body></html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIVCode/Const.html b/LectureCodeExamples/Week1/JavaScriptIVCode/Const.html new file mode 100755 index 0000000000000000000000000000000000000000..8efef20e839c2cd8df2276915fbc21e6e7335c21 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIVCode/Const.html @@ -0,0 +1,26 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>const example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + const MAX_TEMP = 4; + + document.writeln("Contant value: " + MAX_TEMP + "<br>"); + document.writeln("Check console") + MAX_TEMP = 6; // See console + } + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIVCode/Hoisting.html b/LectureCodeExamples/Week1/JavaScriptIVCode/Hoisting.html new file mode 100755 index 0000000000000000000000000000000000000000..b54f3db34e4f7fbd1a67c7cdcc8b4311dd92e356 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIVCode/Hoisting.html @@ -0,0 +1,31 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>Scope example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + let value = 200; /* Try with 10 */ + document.writeln("Result in main: " + evaluate(value)); + } + + function evaluate(x) { + /* y is hoisted */ + document.writeln("Value of y in evaluate is: " + y + "<br>"); + + if (x >= 100) { + var y = x * 100; + document.writeln("Inside of if value of y is: " + y + "<br>"); + } + return y; // Accessible + } + </script> +</body> +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIVCode/NullAndUndefined.html b/LectureCodeExamples/Week1/JavaScriptIVCode/NullAndUndefined.html new file mode 100755 index 0000000000000000000000000000000000000000..5c16e75a644601795707f5cbdfd38031576614c1 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIVCode/NullAndUndefined.html @@ -0,0 +1,29 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>typeof and instanceof</title> + </head> + + <body> + <script> + "use strict"; + let address = { + street: "PaintBranch", + city: "College Park", + }; + + let answer = "typeof null →" + typeof null + "<br>"; + answer += "typeof undefined →" + typeof undefined + "<br>"; + answer += + "Value returned by function →" + printSchoolName() + "<br>"; + answer += "apt property does not exist → " + address["apt"] + "<br>"; + document.writeln(answer); + + function printSchoolName() { + let answer = "UMCP"; + /* Missing return on purpose */ + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIVCode/NumericValues.html b/LectureCodeExamples/Week1/JavaScriptIVCode/NumericValues.html new file mode 100755 index 0000000000000000000000000000000000000000..7b3be650f78bdf27966eb7a39175c2b1aa306630 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIVCode/NumericValues.html @@ -0,0 +1,49 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>Numeric Values</title> +</head> + +<body> + <script> + "use strict"; + + let info = "NaN: " + Number.NaN + "<br>"; + info += "Infinity: " + Infinity + "<br>"; + info += "MAX_VALUE: " + Number.MAX_VALUE + "<br>"; + info += "MIN_VALUE: " + Number.MIN_VALUE + "<br>"; + info += "POSITIVE_INFINITY: " + Number.POSITIVE_INFINITY + "<br>"; + info += "NEGATIVE_INFINITY: " + Number.NEGATIVE_INFINITY + "<br>"; + info += "isFinite(100): " + isFinite(100) + "<br>"; + info += "Number(null): " + Number(null) + "<br>"; + info += "window.isFinite(null): " + window.isFinite(null) + "<br>"; + info += "Number.isFinite(null): " + Number.isFinite(null) + "<br>"; + + document.writeln(info); + + document.writeln("Result of 1/0: " + 1 / 0 + "<br>"); + document.writeln("Result of 1/Infinity: " + 1 / Infinity + "<br>"); + document.writeln("Result of Infinity/0: " + Infinity / 0 + "<br>"); + document.writeln("Result of Infinity/Infinity: " + Infinity / Infinity + + "<br>"); + document.writeln("Square root of negative value: " + Math.sqrt(-10) + + "<br>"); + document.writeln("Square root of a string: " + Math.sqrt("Rose") + "<br>"); + + document.writeln("Floating-point values are approximations<br>"); + let x = 1 / 7 + 4 / 7 + 2 / 7; + let y = (1 + 4 + 2) / 7; + document.writeln("Value of x: " + x + "<br>"); + document.writeln("Value of y: " + y + "<br>"); + document.writeln("Comparison of x and y:<br>"); + if (x === y) { + document.writeln("Same value<br>"); + } else { + document.writeln("Different values<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIVCode/TruthyFalsy.html b/LectureCodeExamples/Week1/JavaScriptIVCode/TruthyFalsy.html new file mode 100755 index 0000000000000000000000000000000000000000..42c408bf01f3617f8c2f85a6f8cbfe59dd4d5909 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIVCode/TruthyFalsy.html @@ -0,0 +1,64 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Truthy Falsy Example</title> + <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"> + </script> +</head> + +<body> + <script> + "use strict"; + + function isTruthy(value, hide) { + let message = ""; + + if (!hide) { + message += value; + } + message += (value ? " is Truthy!": " is Falsy!"); + document.writeln(message + "<br>"); + } + + document.writeln("********** FIRST SET (all falsy) **********<br>"); + isTruthy(false); + isTruthy(0); + document.write("Empty string:"); isTruthy(""); + isTruthy(null); + isTruthy(undefined); + isTruthy(NaN); + + document.writeln("<br>********** SECOND SET (all truthy) **********<br>"); + document.write(`"0"`); isTruthy("0", true); + document.writeln(`"false"`); isTruthy("false", true); + document.write(`{}`);isTruthy({}, true); + document.write(`[]`);isTruthy([], false); + isTruthy(Math.PI); + isTruthy("Hello everyone"); + + document.writeln("<br>********** THIRD SET **********<br>"); + let date1 = new Date('2020-09-21T12:30:00'); + let date2 = new Date('September 21, 2020 12:30:00') + document.writeln(`date1: ${date1}`);isTruthy(date1, true); + document.writeln(`date2: ${date2}`);isTruthy(date1, true); + + document.writeln(`date1 == date2 ${date1 == date2}<br>`); + document.writeln(`date1 === date2 ${date1 === date2}<br>`); + + + document.writeln("<br>********** FOURTH SET (using Lodash) **********<br>"); + /* Using Lodash function lib. isEqual performs deep comparison */ + document.writeln(`_.isEqual(date1, date2): ${_.isEqual(date1, date2)}<br>`); + + document.writeln("<br>********** FIFTH SET (current date) **********<br>"); + let now = new Date(); + document.writeln(`now→${now}<br>`); + document.writeln(`isTruthy(now)`); isTruthy(now, true); + document.writeln(now); + + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIVCode/TypeOfInstanceOf.html b/LectureCodeExamples/Week1/JavaScriptIVCode/TypeOfInstanceOf.html new file mode 100755 index 0000000000000000000000000000000000000000..e32e0699a5fc8f1e875b132137697f2ff35da781 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIVCode/TypeOfInstanceOf.html @@ -0,0 +1,51 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>typeof and instanceof</title> +</head> + +<body> + <script> + "use strict"; + + const myInfoObj = { + name: "John", + id: 10 + }; + const scoresArray = [10, 30]; + let name = "Peter", gpa = 4.0, hungry = true; + let myUndefinedVariable; + let myNullVariable = null; + let mySymbol = Symbol("A"); + + document.writeln("<h2>typeof examples</h2>"); + document.writeln("typeof name: " + typeof name + "<br>"); + document.writeln("typeof gpa: " + typeof gpa + "<br>"); + document.writeln("typeof hungry: " + typeof hungry + "<br>"); + document.writeln("typeof myUndefinedVariable: " + typeof myUndefinedVariable + "<br>"); + document.writeln("typeof myNullVariable: " + typeof myNullVariable + "<br>"); + + document.writeln("typeof mySymbol: " + typeof mySymbol + "<br>"); + document.writeln("typeof myInfoObj: " + typeof myInfoObj + "<br>"); + document.writeln("typeof scoresArray: " + typeof scoresArray + "<br>"); + document.writeln("typeof printSchoolName: " + typeof printSchoolName + "<br><br>"); + + document.writeln("<h2>instanceof examples</h2>"); + document.writeln("myInfoObj instance of Object: " + (myInfoObj instanceof Object) + "<br>"); + document.writeln("scoresArray instance of Object: " + (scoresArray instanceof Object) + "<br>"); + document.writeln("scoresArray instance of Array: " + (scoresArray instanceof Array) + "<br>"); + document.writeln("printArray instance of Function: " + (printSchoolName instanceof Function) + "<br><br>"); + + document.writeln("<h2>Array.isArray</h2>"); + document.writeln("Array.isArray(myInfoObj): " + Array.isArray(myInfoObj) + "<br>"); + document.writeln("Array.isArray(scoresArray): " + Array.isArray(scoresArray) + "<br>"); + document.writeln("Array.isArray(printSchoolName): " + Array.isArray(printSchoolName) + "<br>"); + + + function printSchoolName() { + document.writeln("UMCP"); + } + </script> +</body></html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/JavaScriptIntroCode/SqrTable.html b/LectureCodeExamples/Week1/JavaScriptIntroCode/SqrTable.html new file mode 100755 index 0000000000000000000000000000000000000000..ffbfde8de89df35df504cd0b6888968506d18074 --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIntroCode/SqrTable.html @@ -0,0 +1,42 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>Square Root Table</title> +</head> + +<body> + <script> + "use strict"; + + let currValue = 0, + maximumValue; + + /* Reading a value from the user and verifying is correct */ + do { + maximumValue = Number(prompt("Enter a value")); + if (maximumValue < 0) { + alert("Invalid value: " + maximumValue); + } + } while (maximumValue < 0); + + /* Generating the table */ + // document.writeln writes a string of text followed by a newline + // character to a document. Try also document.write(...) + document.writeln("<table border=\"2\">"); + document.writeln("<caption><strong>Square Root Table</strong></caption>"); + document.writeln("<tr><th>Number</th><th>Square Root</th></tr>"); + + while (currValue <= maximumValue) { + document.writeln("<tr><td>" + currValue + "</td><td>"); + document.writeln(Math.sqrt(currValue) + "</td></tr>"); + currValue = currValue + 1; + } + + document.writeln("</table>"); + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/JavaScriptIntroCode/TemplateJS.html b/LectureCodeExamples/Week1/JavaScriptIntroCode/TemplateJS.html new file mode 100755 index 0000000000000000000000000000000000000000..396ae523a3f55c82f804810e4b2c8524b9e7cb3b --- /dev/null +++ b/LectureCodeExamples/Week1/JavaScriptIntroCode/TemplateJS.html @@ -0,0 +1,24 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JavaScript Program Template</title> +</head> + +<body> + <script> + // "use strict"; Defines that JavaScript code should be executed in strict mode. + + "use strict"; + + let value = 10; + console.log("value is: " + value); + document.writeln("Output available in the console"); + + /* Your JavaScript here */ + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/ObjsOpsCode/AndOrCoalescing.html b/LectureCodeExamples/Week1/ObjsOpsCode/AndOrCoalescing.html new file mode 100755 index 0000000000000000000000000000000000000000..7f43a6dd5181559369a5cb5c5a0066c0447863b6 --- /dev/null +++ b/LectureCodeExamples/Week1/ObjsOpsCode/AndOrCoalescing.html @@ -0,0 +1,72 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>JS Example</title> + </head> + <body> + <script> + function printValueAnd(val1, val2) { + document.writeln(`${val1} && ${val2}: ${val1 && val2}<br>`); + } + + function printValueOr(val1, val2) { + document.writeln(`${val1} || ${val2}: ${val1 || val2}<br>`); + } + + function printName(name) { + document.writeln(`printName argument ${name}, `); + // name = name || "No name"; + name ||= "No name"; // equivalent to previous one + document.writeln(`printName result: ${name}<br>`); + } + + function printQuantityRequested(quantity) { + document.writeln(`printQualityRequested argument ${quantity}, `); + quantity ||= 18; + document.writeln(`printQuantity result: ${quantity}<br>`); + } + + function printQuantityRequestedCorrect(quantity) { + document.writeln(`printQualityRequestedCorrect argument ${quantity}, `); + // quantity = quantity ?? 18; + quantity ??= 18; + document.writeln(`printQuantityCorrect result: ${quantity}<br>`); + } + + printValueAnd(10, 20); + printValueAnd(20, 10); + printValueAnd(true, 10); + printValueAnd(false, 10); + printValueAnd(undefined, 10); + printValueAnd(null, 10); + document.writeln("==========<br>"); + + printValueOr(10, 20); + printValueOr(20, 10); + printValueOr(true, 10); + printValueOr(false, 10); + printValueOr(undefined, 10); + printValueOr(null, 10); + document.writeln("==========<br>"); + + printName("Mary"); + printName(null); + printName(undefined); + document.writeln("==========<br>"); + + printQuantityRequested(20); + printQuantityRequested(null); + printQuantityRequested(); + printQuantityRequested(undefined); + printQuantityRequested(0); // problem!!! + document.writeln("==========<br>"); + + printQuantityRequestedCorrect(20); + printQuantityRequestedCorrect(null); + printQuantityRequestedCorrect(); + printQuantityRequestedCorrect(undefined); + printQuantityRequestedCorrect(0); + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/ObjsOpsCode/CallbackCorrect.html b/LectureCodeExamples/Week1/ObjsOpsCode/CallbackCorrect.html new file mode 100755 index 0000000000000000000000000000000000000000..4a6f1104dd24ecb6b9eb26b7619025e9feb9f88c --- /dev/null +++ b/LectureCodeExamples/Week1/ObjsOpsCode/CallbackCorrect.html @@ -0,0 +1,31 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>Callback example</title> +</head> + +<body> + <script> + function loadScript(src, callback) { + let script = document.createElement("script"); + script.src = src; + document.head.append(script); + script.onload = callback; + } + + loadScript( + "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js", + () => { + document.writeln(`Library loaded</h1>`); + const arr1 = ['a', 'b', 'c']; + const arr2 = ['e', 'a', 'c']; + document.writeln(_.intersection(arr1, arr2)); + }); + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/ObjsOpsCode/CallbackIncorrect.html b/LectureCodeExamples/Week1/ObjsOpsCode/CallbackIncorrect.html new file mode 100755 index 0000000000000000000000000000000000000000..ab0e3cdcd630303d17c9b7c249b41db98b9d8b88 --- /dev/null +++ b/LectureCodeExamples/Week1/ObjsOpsCode/CallbackIncorrect.html @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>Callback example</title> +</head> + +<body> + <script> + function loadScript(src) { + let script = document.createElement("script"); + script.src = src; + document.head.append(script); + } + + loadScript("https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"); + document.writeln(`Library loaded (?????), Check console</h1>`); + const arr1 = ['a', 'b', 'c']; + const arr2 = ['e', 'a', 'c']; + document.writeln(_.intersection(arr1, arr2)); // ReferenceError: _ is not defined + </script> +</body> + +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/ObjsOpsCode/ChainingOp.html b/LectureCodeExamples/Week1/ObjsOpsCode/ChainingOp.html new file mode 100755 index 0000000000000000000000000000000000000000..3f98d8a369bd8aad347ebdadb8138d6f84d7b830 --- /dev/null +++ b/LectureCodeExamples/Week1/ObjsOpsCode/ChainingOp.html @@ -0,0 +1,53 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>JS Example</title> + </head> + <body> + <script> + + /* Defining two students with different pieces of information */ + + const mary = { + name: "Mary", + address: { + city: "College Park", + state: "Maryland", + budget: { + local: 340, + federal: 500, + }, + }, + }; + + const peter = { + name: "Peter" + }; + + function printInfoWrong(student) { + let answer = `Printing info for ${student.name} `; + + answer += ` ${student.address.city} ${student.address.state}<br>`; + + document.writeln(`printInfoWrong - ${answer}<br>`); + } + + function printInfoCorrect(student) { + let answer = `Printing info for ${student?.name} `; + + answer += ` Budget: `; + answer += `Local: ${student.address?.budget?.local}, Federal: ${student.address?.budget?.federal}<br>`; + + document.writeln(`printInfoCorrect- ${answer}<br>`); + } + + printInfoWrong(mary); + // printInfoWrong(peter); /* Uncomment and check console to see problem */ + + printInfoCorrect(mary); + printInfoCorrect(peter); + + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/ObjsOpsCode/ExtendedArray.html b/LectureCodeExamples/Week1/ObjsOpsCode/ExtendedArray.html new file mode 100755 index 0000000000000000000000000000000000000000..3d4870029ccb7ef86c7573e7e02ab90b337c8622 --- /dev/null +++ b/LectureCodeExamples/Week1/ObjsOpsCode/ExtendedArray.html @@ -0,0 +1,60 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>ES6 Class Example</title> + </head> + + <body> + <script> + class MyArray extends Array { + isEmpty() { + return this.length === 0; + } + } + + class StoreBranch { + #name; + #established; + #location; + #sales; + constructor(name, established, location, sales) { + this.#name = name; + this.#established = established; + this.#location = location; + this.#sales = sales; + } + + [Symbol.toPrimitive]() { + return `${this.#name}-${this.#location}`; + } + } + + let firstStore = new StoreBranch( + "Wendy's", + new Date("1995"), + "Greenbelt", + 1000 + ); + let stores = new MyArray( + firstStore, + new StoreBranch("Wendy's", new Date("2005"), "College Park", 3000), + new StoreBranch("Wendy's", new Date("1985"), "Austin", 600) + ); + + document.writeln("All the stores<br>"); + stores.forEach((store) => document.writeln(store + "<br>")); + + let salesLowerValue = 1000; + let storesWithGoodSales = stores.filter( + (sb) => sb.sales >= salesLowerValue + ); + document.writeln( + `Stores with sales of least ${salesLowerValue}: ${storesWithGoodSales}<br>` + ); + document.writeln(`Array is empty? ${storesWithGoodSales.isEmpty()}<br>`); + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/ObjsOpsCode/ExtensibleSealed.html b/LectureCodeExamples/Week1/ObjsOpsCode/ExtensibleSealed.html new file mode 100755 index 0000000000000000000000000000000000000000..049530e211aea5dc979c18c89eec25414cb5b65f --- /dev/null +++ b/LectureCodeExamples/Week1/ObjsOpsCode/ExtensibleSealed.html @@ -0,0 +1,46 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + let student = new Object(); + student.name = "Rose"; + Object.preventExtensions(student); + + document.writeln("***** preventExtensions *****") + // student.gpa = 3.2; // NOT Allowed + student.name = "Mark"; + document.writeln("<br />gpa: " + student.gpa); + document.writeln("<br />name: " + student.name); + + /* We can delete properties of object we prevented extensions */ + delete student.name; + document.writeln("<br />name (after deleting): " + student.name); + + document.writeln("<br><br>***** sealing object *****") + /* Sealing the object */ + let game = new Object(); + game.name = "SuperTetris"; + Object.seal(game); + + // game.year = 2000; // NOT Allowed + // delete game.name; // NOT Allowed + document.writeln("<br />Game name: " + game.name); + document.writeln("<br />Extensible: " + Object.isExtensible(game)); + document.writeln("<br />Sealed: " + Object.isSealed(game)); + + /* Can still change the value */ + game.name = "AnotherTetris"; + document.writeln("<br />After changing name: " + game.name); + } + </script> +</body> +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/ObjsOpsCode/Freeze.html b/LectureCodeExamples/Week1/ObjsOpsCode/Freeze.html new file mode 100755 index 0000000000000000000000000000000000000000..475e83cf90244ada6d19c3c39eaa203602200181 --- /dev/null +++ b/LectureCodeExamples/Week1/ObjsOpsCode/Freeze.html @@ -0,0 +1,30 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>Freezin object</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + let school = new Object(); + let info; + + school.name = "UMCP"; + school.city = "College Park"; + Object.freeze(school); + + // school.name = "UMD"; // modifying NOT Allowed (Generates error) + // delete school.city; // deleting NOT Allowed (Generates error) + // school.mascot = "terp"; // adding NOT Allowed (Generates error) + + info = school.name + " " + school.city; + document.writeln(info); + } + </script> +</body> +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ArrayEverySome.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ArrayEverySome.html new file mode 100755 index 0000000000000000000000000000000000000000..26ced7bf98de37d91525fcde879723ae6c4e1afc --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ArrayEverySome.html @@ -0,0 +1,33 @@ +<!doctype html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Array every and some method Example</title> +</head> + +<body> + <script> + "use strict"; + + /* Index and array are optional */ + function isOdd(elem, index, array) { + document.write(`elem: ${elem} index: ${index} array: ${array}<br>`); + return (elem % 2 === 1); + } + let value = 1; /* Try 2 */ + let atLeastOneOdd = [2, 6, 8, value, 4].some(isOdd); + document.writeln("=====<br>"); + let allOdd1 = [2, 6, 8, 1, 4].every(isOdd); + document.writeln("=====<br>"); + let allOdd2 = [1, 3, 5, 9, 7].every(isOdd); + document.writeln("=====<br>"); + + document.writeln("atLeastOneOdd: " + atLeastOneOdd + "<br>"); + document.writeln("allOdd1: " + allOdd1 + "<br>"); + document.writeln("allOdd2: " + allOdd2 + "<br>"); + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ArrayForEachFindFindIndex.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ArrayForEachFindFindIndex.html new file mode 100755 index 0000000000000000000000000000000000000000..cb39efb0b31cc5e3a0876b24f8f4fa0e2250c318 --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ArrayForEachFindFindIndex.html @@ -0,0 +1,66 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS forEach, find, findIndex</title> +</head> + +<body> + <script> + "use strict"; + + document.writeln("***** <strong>Example #1</strong> Result of processing with forEach "); + document.writeln("(with 2-parameter function) *****<br>"); + let fruits = ["apple", "pear", "banana", "orange", "plum", "grape"]; + fruits[7] = "strawberry"; /* Added leaving undefined element in between */ + + document.writeln(`Original array: ${fruits.join()}<br>`); + fruits.forEach(function(elem, index) { + document.writeln(`Index: ${index}, Elem: ${elem}<br>`); + }); + + document.writeln("<br>**** Using arrow function<br>"); + fruits.forEach((elem, index) => { + document.writeln(`Index: ${index}, Elem: ${elem}<br>`); + }); + + document.writeln("<br>**** <strong>Example #2</strong> Result of processing with forEach "); + document.writeln("(with with 1-parameter function) *****<br>"); + fruits.forEach(elem => { + document.writeln(`Elem: ${elem}<br>`); + }); + + + document.writeln("<br>***** <strong>Example #3</strong> Result of processing with find "); + document.writeln(" finding fruit's name with minimum length) *****<br>"); + fruits = ["apple", "pear", "banana", "orange", "plum", "grape"]; + document.writeln("Original array: " + fruits.join() + "<br>"); + let targetLength = 6; /* Try with 8 */ + let result = fruits.find(elem => { + return elem.length >= targetLength; + }); + if (result !== undefined) { + document.writeln(`First fruit with length ${targetLength} is ${result}`); + } else { + document.writeln("Not found"); + } + document.writeln("<br>"); + + + document.writeln("<br>***** <strong>Example #4</strong> Result of processing with findIndex "); + document.writeln("finding fruit's name with minimum length) *****<br>"); + fruits = ["apple", "pear", "banana", "orange", "plum", "grape"]; + document.writeln("Original array: " + fruits.join() + "<br>"); + targetLength = 6; /* Try with 8 */ + let resultIndex = fruits.findIndex(elem => { + return elem.length >= targetLength; + }); + if (resultIndex !== -1) { + document.writeln(`First fruit with length ${targetLength} is ${fruits[resultIndex]}`); + } else { + document.writeln("Not found"); + } + document.writeln("<br>"); + </script> +</body></html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ArrayMap.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ArrayMap.html new file mode 100755 index 0000000000000000000000000000000000000000..845e05d310cd11e58ce66dd2753141b52552f55a --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ArrayMap.html @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Array map method Example</title> +</head> + +<body> + <script> + "use strict"; + + document.writeln("***** <strong>Example #1</strong> Using map function to double values *****<br>"); + let numbers = [2, 30, 44, 5]; + let doubles = numbers.map(num => { + return num * 2; + }); + document.writeln(`Original array: ${numbers.join()}<br>`); + document.writeln(`New array: ${doubles.join()} <br><br>`); + + document.writeln("*****<strong>Example #2</strong> Using map function to triple values *****<br>"); + let triples = numbers.map(n => n * 3); + document.writeln(`Original array: ${numbers.join("-")} <br>`); + document.writeln(`New array: ${triples.join("-")}`); + + </script> +</body></html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/DefaultParameters.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/DefaultParameters.html new file mode 100755 index 0000000000000000000000000000000000000000..79756d7433e39b83a905f0855bbc042ea3036fa4 --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/DefaultParameters.html @@ -0,0 +1,48 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + taskOldApproach(); + task(); + task("Rose"); + task(25); + task("Kelly", 30, 20000); + + document.writeln(greet('Welcome to CS', 'Chris')); + } + + function taskOldApproach(name, age) { + name = name || "John"; /* Trick to define a default value */ + age = age || 21; + document.writeln("Old approach: " + name + ' ' + age + "<br>"); + } + + function task(name = "John", age = 21, salary = special()) { + document.writeln(name + ' ' + age + ' ' + salary + "<br>"); + } + + function special() { + return 10000; + } + + /* Parameters defined beforehand (to the left) are available to later + default parameters */ + function greet(greeting, name, message = `Dear ${name}: ${greeting}`) { + return [greeting, name, message]; + } + + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/Filter.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/Filter.html new file mode 100755 index 0000000000000000000000000000000000000000..622611f8540036d50aaaad2fa04c58b978786695 --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/Filter.html @@ -0,0 +1,25 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Filter Method</title> +</head> + +<body> + <script> + "use strict"; + + document.writeln("***** <strong>Example #1</strong> Using map function to double values *****<br>"); + let numbers = [2, 7, 30, 44, 5]; + let evenValues = numbers.filter(num => num % 2 === 0); + document.writeln(`Original array: ${numbers}<br>`); + document.writeln(`New array: ${evenValues} <br><br>`); + + document.writeln("*****<strong>Example #2</strong> Using map function to triple values *****<br>"); + let names = ["Rose", "Peter", "Bob", "Al", "Kathy"] + let greaterThan = names.filter(name => name.localeCompare("Kathy") > 0); + document.writeln(`Original array: ${names} <br>`); + document.writeln(`New array: ${greaterThan}`); + </script> +</body></html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ForMapIndex.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ForMapIndex.html new file mode 100755 index 0000000000000000000000000000000000000000..ff4aef398b9cd7f57f5f90dc0a463fff9f7747f9 --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ForMapIndex.html @@ -0,0 +1,51 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>JS Example</title> + <script> + "use strict"; + let data=[77, 88, 99]; + let initialValue = 0; + + document.writeln("<br>========= forEach =========<br>"); + let result = data.forEach((elem, index, array) => { + document.writeln(`elem: ${elem}<br>`); + document.writeln(`index: ${index}<br>`); + document.writeln(`array: ${array}<br>`); + document.writeln("*** next ***<br>"); + }); + document.writeln(`Result ${result}<br>`); + + document.writeln("<br>========= map =========<br>"); + result = data.map((elem, index, array) => { + document.writeln(`elem: ${elem}<br>`); + document.writeln(`index: ${index}<br>`); + document.writeln(`array: ${array}<br>`); + document.writeln("*** next ***<br>"); + // return elem; // uncomment to add elem to result + }); + document.writeln(`Result ${result}<br>`); + + document.writeln("<br>========= filter =========<br>"); + result = data.filter((elem, index, array) => { + document.writeln(`elem: ${elem}<br>`); + document.writeln(`index: ${index}<br>`); + document.writeln(`array: ${array}<br>`); + document.writeln("*** next ***<br>"); + // return true; // uncomment to add elem to result + }); + document.writeln(`Result ${result}<br>`); + + document.writeln("<br>========= every =========<br>"); + result = data.every((elem, index, array) => { + document.writeln(`elem: ${elem}<br>`); + document.writeln(`index: ${index}<br>`); + document.writeln(`array: ${array}<br>`); + document.writeln("*** next ***<br>"); + // return true; // uncomment to return true + }); + document.writeln(`Result ${result}<br>`); + </script> +</head> +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/Reduce.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/Reduce.html new file mode 100755 index 0000000000000000000000000000000000000000..b3132c9729554063334376971deff0ce21157838 --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/Reduce.html @@ -0,0 +1,67 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>JS Example</title> +</head> +<body> + <script> + "use strict"; + let initialValue = 0; + let data = [2, 2, 3]; + + document.writeln("<br>========= Case 1 (Sum) =========<br>"); + const sum = data.reduce((result, elem) => { + return result + elem; + }, initialValue); + document.writeln(`Sum: ${sum}`); + + initialValue = 1; + data = [2, 2, 3]; + document.writeln("<br>========= Case 2 (Product) =========<br>"); + const product = data.reduce((result, elem) => { + return result * elem; + }, initialValue); + document.writeln(`Product: ${product}`); + + data = [2, 2, 3]; + document.writeln("<br>========= Case 3 (Product (no initialValue)) =========<br>"); + const product2 = data.reduce((result, elem) => { + return result * elem; + }); + document.writeln(`Product: ${product2}`); + + data=[77, 88, 99]; + initialValue = 0; + document.writeln("<br>========= Case 4 (with initialValue)=========<br>"); + data.reduce((result, elem, index, array) => { + document.writeln(`result: ${result}<br>`); + document.writeln(`elem: ${elem}<br>`); + document.writeln(`index: ${index}<br>`); + document.writeln(`array: ${array}<br>`); + document.writeln("*** next ***<br>"); + }, initialValue); + + document.writeln("<br>========= Case 5 (no initialValue)=========<br>"); + data.reduce((result, elem, index, array) => { + document.writeln(`result: ${result}<br>`); + document.writeln(`elem: ${elem}<br>`); + document.writeln(`index: ${index}<br>`); + document.writeln(`array: ${array}<br>`); + document.writeln("*** next ***<br>"); + }); + + document.writeln("<br>========= Case 6 (returning 20)=========<br>"); + data.reduce((result, elem, index, array) => { + document.writeln(`result: ${result}<br>`); + document.writeln(`elem: ${elem}<br>`); + document.writeln(`index: ${index}<br>`); + document.writeln(`array: ${array}<br>`); + document.writeln("*** next ***<br>"); + return 20; + }, initialValue); + + + </script> +</body> +</html> \ No newline at end of file diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ReduceObject.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ReduceObject.html new file mode 100755 index 0000000000000000000000000000000000000000..f417c7d3cbd050af670441647a0c6568cd408bc9 --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/ReduceObject.html @@ -0,0 +1,41 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>JS Example</title> + </head> + <body> + <script> + "use strict"; + const employees = [ + { + name: "John", + salary: 10000, + }, + { + name: "Kelly", + salary: 50000, + }, + { + name: "Sarah", + salary: 2000, + }, + ]; + + const totalSalary = employees.reduce((result, elem) => { + return result + elem.salary; + }, 0); + document.writeln(`totalSalary: ${totalSalary}<br>`); + + const avgSalary = employees.reduce((result, elem) => { + return result + elem.salary / employees.length; + }, 0); + document.writeln(`avgSalary: ${avgSalary}<br>`); + + const maxSalary = employees.reduce((result, elem) => { + return result > elem.salary ? result : elem.salary; + }, 0); + document.writeln(`maxSalary: ${maxSalary}<br>`); + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/RestOperator.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/RestOperator.html new file mode 100755 index 0000000000000000000000000000000000000000..7c3e7146d0f7b2a5d84d8193e030cb954be38954 --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/RestOperator.html @@ -0,0 +1,21 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>JS Rest Operator Example</title> + </head> + + <body> + <script> + "use strict"; + + partyInfo("FirstParty", "Ali", "Theresa", "Arushi"); + document.writeln("<br>*****<br>"); + partyInfo("SecondParty", "Josh", "Trenton"); + function partyInfo(partyName, host, ...guests) { + document.writeln(`Party name: ${partyName}, Host: ${host}<br>`); + document.writeln(`Guests: ${guests}`); + } + </script> + </body> +</html> diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/Set.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/Set.html new file mode 100755 index 0000000000000000000000000000000000000000..f46d20751053f42e6869a064c7ac9d95906d3e62 --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/Set.html @@ -0,0 +1,61 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Set Example</title> +</head> + +<body> + <script> + "use strict"; + + /* Notice the use of const instead of let */ + const mySet = new Set(); + const student1 = { + name: "Mike", + id: 10 + }; + const student2 = { + name: "Rose", + id: 20 + }; + document.writeln("<strong>Example #1</strong> Adding entries to set<br><br>"); + mySet.add(150); + mySet.add(student1).add(student2); /* Add is chainable */ + document.writeln("Set size: " + mySet.size + "<br>"); + document.writeln("Set Entries<br>"); + for (let entry of mySet) { + document.writeln(entry + "<br>"); + } + document.writeln("150 part of the set? " + mySet.has(150) + "<br><hr>"); + + + document.writeln("<br><strong>Example #2</strong> After deleting an entry<br><br>"); + mySet.delete(student1); + for (let entry of mySet) { + document.writeln(entry + "<br>"); + } + document.writeln("<hr>"); + + + document.writeln("<br><strong>Example #3</strong> After clearing the set<br>"); + mySet.clear(); + for (let entry of mySet) { + document.writeln(entry + "<br>"); + } + document.writeln("<hr>"); + + + document.writeln("<br><strong>Example #4</strong> Set based on array (removing duplicates)<br>"); + let arr = ["C", "JavaScript", "Pascal", "Pascal", "C", "Nava"]; + document.writeln(`Array: ${arr}<br>`); + let setFromArray = new Set(arr); + document.writeln("Iterating over set:<br>"); + for (let value of setFromArray) { + document.writeln(`${value}<br>`); + } + </script> +</body> + +</html> diff --git a/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/SpreadOperator.html b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/SpreadOperator.html new file mode 100755 index 0000000000000000000000000000000000000000..c70c52f04e112dca18631d352659bc1caf4d21b7 --- /dev/null +++ b/LectureCodeExamples/Week1/RestSpreadOpsArrayFuncCode/SpreadOperator.html @@ -0,0 +1,56 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="utf-8"> + <title>JS Spread Operator Example</title> +</head> + +<body> + <script> + "use strict"; + + process(1, 10, 2, "DataTestOne"); + process(...[1, 10, 2, "DataTestTwo", "DataTestThree"]); + process(1, ...[10, 2], "DataTestFour"); /* will not work without spread operator */ + + function process(start, end, delta, message) { + document.writeln(message + "<br>"); + for (let i = start; i <= end; i += delta) { + document.writeln(i + " "); + } + document.writeln("<br>"); + + document.writeln("arguments.length: " + arguments.length + "<br>"); + document.writeln("arguments[arguments.length - 1]: " + arguments[arguments.length - 1]) + document.writeln("<br>### Arguments: ###<br>"); + for (let val of arguments) { + document.writeln(`Argument: ${val}|`); + } + document.writeln("<br>***** END *****<br><br>"); + + } + + document.writeln("***** Combining arrays *****<br>"); + let part1 = ["C", "Java"]; + let part2 = ["Python"]; + let combined = [...part1, ...part2]; + document.writeln(combined.join() + "<br><br>"); + + + document.writeln("***** Computing maximum of arrays *****<br>"); + let numArray1 = [1, -21, 3, 4]; + let numArray2 = [9, 3, -8, 10, 7]; + document.writeln(`Maximum is: ${Math.max(...numArray1, ...numArray2)}<br><br>`); + + + document.writeln("***** Breaking Strings *****<br>"); + let string = "CMSCXYZ"; + let charArray = [...string]; + document.writeln(`Original: ${string}<br>`); + document.writeln(`As array: ${charArray}<br>`); + document.writeln(`Type of character: ${typeof charArray[0]}<br>`); + </script> +</body> + +</html> diff --git a/LectureSlides/Week1/JSObjectsFetch.pdf b/LectureSlides/Week1/JSObjectsFetch.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b1df5d6934c70b5e670b75cc5bf05a937c6a9e74 Binary files /dev/null and b/LectureSlides/Week1/JSObjectsFetch.pdf differ diff --git a/LectureSlides/Week1/JavaScriptII.pdf b/LectureSlides/Week1/JavaScriptII.pdf new file mode 100644 index 0000000000000000000000000000000000000000..4cf1347d1b24645a17377f75a164e4bc8aa593f2 Binary files /dev/null and b/LectureSlides/Week1/JavaScriptII.pdf differ diff --git a/LectureSlides/Week1/JavaScriptIII.pdf b/LectureSlides/Week1/JavaScriptIII.pdf new file mode 100644 index 0000000000000000000000000000000000000000..04c80922ae5d370c25579ea81e43286129cd45fc Binary files /dev/null and b/LectureSlides/Week1/JavaScriptIII.pdf differ diff --git a/LectureSlides/Week1/JavaScriptIV.pdf b/LectureSlides/Week1/JavaScriptIV.pdf new file mode 100644 index 0000000000000000000000000000000000000000..c84eb8c71f2b4de399f350403f6319668b11605a Binary files /dev/null and b/LectureSlides/Week1/JavaScriptIV.pdf differ diff --git a/LectureSlides/Week1/JavaScriptIntro.pdf b/LectureSlides/Week1/JavaScriptIntro.pdf new file mode 100644 index 0000000000000000000000000000000000000000..ce20b8bd8525268e730e2bd42162767ce457a3f7 Binary files /dev/null and b/LectureSlides/Week1/JavaScriptIntro.pdf differ diff --git a/LectureSlides/Week1/ObjsOps.pdf b/LectureSlides/Week1/ObjsOps.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b8626fd30a0f442293be3821e37bca462a557972 Binary files /dev/null and b/LectureSlides/Week1/ObjsOps.pdf differ diff --git a/LectureSlides/Week1/RestSpreadOpsArrayFunc.pdf b/LectureSlides/Week1/RestSpreadOpsArrayFunc.pdf new file mode 100644 index 0000000000000000000000000000000000000000..77b16a85195cab8f3128f21e237c50ffb1e78f6f Binary files /dev/null and b/LectureSlides/Week1/RestSpreadOpsArrayFunc.pdf differ