diff --git a/codeExamples/week1/EventsJSClassesCode/AccessingElementEventOcurred.html b/codeExamples/week1/EventsJSClassesCode/AccessingElementEventOcurred.html new file mode 100755 index 0000000000000000000000000000000000000000..21e2924585ba4b3395d6e960f439325540cd4423 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/AccessingElementEventOcurred.html @@ -0,0 +1,52 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <div id="OuterElement"> + This text is part of the + outer element.<br><br><br> + <div id="InnerElement"> +   This text is part of the inner element.<br><br><br> + <div id="WayInnerElement"> +       This text is part of the way inner element :)<br><br><br> + </div> + </div> + </div> + <script> + /* This refers to the element on which the event handler is registered and it does need to be + * the element on which the event occurs */ + + let outerElement = document.getElementById("OuterElement"); + let innerElement = document.getElementById("InnerElement"); + let wayInnerElement = document.getElementById("WayInnerElement"); + + outerElement.addEventListener("click", function (event) { + + if (this == outerElement) { + alert("this is refering to outerElement"); + } else if (this == innerElement) { + alert("this is referring to innerElement"); + } else if (this == wayInnerElement) { + alert("this is referring to wayInnerElement"); + } else { + alert("other"); + } + if (event.target == outerElement) { + alert("outerElement was the target"); + } else if (event.target == innerElement) { + alert("innerElement was the target"); + } else if (event.target == wayInnerElement) { + alert("wayInnerElement was the target"); + } else { + alert("Other"); + } + }); + //innerElement.addEventListener("click", () => alert("InnerElement")); + //wayInnerElement.addEventListener("click", () => alert("WayInnerElement")); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/ArrayMethods1.html b/codeExamples/week1/EventsJSClassesCode/ArrayMethods1.html new file mode 100755 index 0000000000000000000000000000000000000000..4c247484e8c49dba5f984e7e05e50739a1c4b5bd --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/ArrayMethods1.html @@ -0,0 +1,31 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <script> + const a = [10, 20, 30]; + a.length = 4; + a[3] = 50; + document.writeln(`a[3]=${a[3]}<br>`); + + /* using foreach to iterate over elements (ignores undefined elements) */ + a.forEach(i => document.writeln(i)); + delete a[0]; + document.writeln("<br>After deleting<br>"); + a.forEach(i=> document.writeln(i)); + document.writeln(`<br>Length: ${a.length}<br>`); + + let removed = a.splice(0, 2); // first argument index, second number elements to remove + // if you don't provide second argument all elements are removed + // until the end of the array. + document.writeln(`array returned by splice: ${removed.join()}<br>`); + document.writeln(`original array after splice: ${a.join()}<br>`); + document.writeln(`original array length after splice: ${a.length}<br>`); + + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/ArrayMethods2.html b/codeExamples/week1/EventsJSClassesCode/ArrayMethods2.html new file mode 100755 index 0000000000000000000000000000000000000000..259062a8997d2ac3d40a08ed7d452906373f4805 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/ArrayMethods2.html @@ -0,0 +1,60 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <script> + const tas = [ + {name: "John", course: "cmsc131", type:"full", hours: 4}, + {name: "Mary", course: "math106", type: "half", hours: 10}, + {name: "Laura", course: "psyc101", type:"full", hours: 3}, + {name: "Kelly", course: "cmsc131", type:"full", hours: 5}, + ]; + + /* forEach is a built-in array method; callback is called on each array element */ + tas.forEach(i => document.writeln(i.name + "<br>")); + + /* mapping - map each item of an array to a new item of new array based on the callback */ + /* We want to retrieve array of courses. */ + const allCourses = tas.map(ta => ta.course); + document.writeln(`TA courses: ${allCourses.join()}<br>`); + + /* Testing items in array */ + /* We want to identify whether all elements of an array satisfy a condition */ + /* every returns true if call back is true for all elements */ + const allFullType = tas.every(ta => ta.type === "full"); + document.writeln(`allFullType:${allFullType}<br>`); + + /* some will applies callback to each element until one is found to be true */ + const anypsyc101TA = tas.some(ta => ta.course === "psyc101"); + document.writeln(`anypsyc101TA:${anypsyc101TA}<br>`); + + /* finding first element in array that satifies condition; undefined returned if none found */ + const tacmsc131 = tas.find(ta => { return ta.name === "John"; }); + document.writeln(`Name: ${tacmsc131.name}, Type: ${tacmsc131.type}<br>`); + + /* filter returns array with items satisfying condition */ + const allcmsc131Tas = tas.filter(ta => ta.course === "cmsc131"); + document.writeln(`allcmsc131Tas:${allcmsc131Tas.map(ta => ta.name).join()}<br>`); + + /* indices */ + const laurasIndex = tas.findIndex(ta => ta.name === "Laura"); + document.writeln(`Laura\'s index ${laurasIndex}<br>`); + + /* visiting every element in the collection and aggregating some value to generate */ + /* a single value from the array */ + + const values = [2, 3, 9]; + const initialValue = 0; + /* reduce has two parameters: callback and initial value */ + const valuesSum = values.reduce((accumulated, curr) => accumulated + curr, initialValue); + document.writeln(`valuesSum:${valuesSum}<br>`); + + const totalHours = tas.reduce((accumulated, curr) => accumulated + curr.hours, initialValue); + document.writeln(`totalHours:${totalHours}<br>`); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/ClassDefinitionDeclaration.html b/codeExamples/week1/EventsJSClassesCode/ClassDefinitionDeclaration.html new file mode 100755 index 0000000000000000000000000000000000000000..257df3a0f9f19306636ccfec1380149a1767f3b8 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/ClassDefinitionDeclaration.html @@ -0,0 +1,50 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + class Student { + constructor(name, age) { + this.name = name; + this.age = age; + } + + toString() { + return this.name + " " + this.age; + } + + getName() { + return this.name; + } + + static getCollegeName() { + return "UMCP"; + } + } + + main(); + + function main() { + let s1 = new Student("Mary", 20); + let s2 = new Student("Peter", 30); + + document.writeln(s1 + "<br>"); + document.writeln(s2 + "<br>"); + + document.writeln("College Name: " + Student.getCollegeName() + "<br>"); + document.writeln("Student's name: " + s1.getName() + "<br>"); + s1.name = "CHANGED NAME"; + document.writeln("Student's name: " + s1.getName() + "<br>"); + + /* Student("Kyle", 40); */ /* Check console when commented out */ + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/ClassDefinitionExpression.html b/codeExamples/week1/EventsJSClassesCode/ClassDefinitionExpression.html new file mode 100755 index 0000000000000000000000000000000000000000..780dd362cc1bd566a61dc336f77ab2863bce496b --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/ClassDefinitionExpression.html @@ -0,0 +1,39 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + let Student = class St { + constructor(studentsName, age) { + this.studentsName = studentsName; + this.age = age; + } + toString() { + return this.studentsName + " " + this.age; + } + + getNameOfClass() { + return St.name; + } + } + + let s1 = new Student("Michael", 101); + let s2 = new Student("Rose", 345); + + document.writeln(s1 + "<br>"); + document.writeln(s2 + "<br>"); + document.writeln("Class name: " + s1.getNameOfClass() + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/ComputePropKeys.html b/codeExamples/week1/EventsJSClassesCode/ComputePropKeys.html new file mode 100755 index 0000000000000000000000000000000000000000..c88a1cd20f23a0bb6141d2ae4c3b68a48bb49f06 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/ComputePropKeys.html @@ -0,0 +1,24 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + let part1 = 'camp', part2 = 'us'; + let preFunc = "getD", postFunc = "ata"; + + let student1 = { + id: 1, + [part1 + part2] : "UMCP", + [preFunc + postFunc]() { return [part1 + part2]; } + }; + + document.writeln("id: " + student1.id + ", campus: " + student1.campus + "<br>"); + document.writeln("Function: " + student1.getData() + "<br>"); + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/EventPropagation.html b/codeExamples/week1/EventsJSClassesCode/EventPropagation.html new file mode 100755 index 0000000000000000000000000000000000000000..2c8c2cb35d24d208737ac9e6dd232296e4ad6b2b --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/EventPropagation.html @@ -0,0 +1,32 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <div id="OuterElement"> + This text is part of the + outer element.<br><br><br> + <div id="InnerElement"> +   This text is part of the inner element.<br><br><br> + <div id="WayInnerElement"> +       This text is part of the way inner element :)<br><br><br> + </div> + </div> + </div> + <script> + /* In some event's model the listener is executed starting at the targeted element */ + /* and bubbling up the DOM tree. This is refered to as event bubbling. In other models */ + /* event handling starts with the top element trickling down the target element. This is referred to + /* as event capturing. W3 Consortium approach relies onhandling an event + /* in two phases: capturing phase (event first trickles down); bubbling phase (after target + /* element has been reached during the capturing phase the event bubbles up). */ + + document.getElementById("OuterElement").addEventListener("click", () => alert("OuterElement")); + document.getElementById("InnerElement").addEventListener("click", () => alert("InnerElement")); + document.getElementById("WayInnerElement").addEventListener("click", () => alert("WayInnerElement")); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/EventPropagationControlled.html b/codeExamples/week1/EventsJSClassesCode/EventPropagationControlled.html new file mode 100755 index 0000000000000000000000000000000000000000..e4704227439dfff2f924d33710851546b7c3fe75 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/EventPropagationControlled.html @@ -0,0 +1,27 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <div id="OuterElement"> + This text is part of the + outer element.<br><br><br> + <div id="InnerElement"> +   This text is part of the inner element.<br><br><br> + <div id="WayInnerElement"> +       This text is part of the way inner element :)<br><br><br> + </div> + </div> + </div> + <script> + /* We can control which event-handling order we want by using a boolean value in addEventLister. */ + /* If the value is false (or not present) bubbling will be used; otherwise capturing */ + document.getElementById("OuterElement").addEventListener("click", () => alert("OuterElement"), true); + document.getElementById("InnerElement").addEventListener("click", () => alert("InnerElement"), true); + document.getElementById("WayInnerElement").addEventListener("click", () => alert("WayInnerElement"), true); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/FunctionContextCorrecta.html b/codeExamples/week1/EventsJSClassesCode/FunctionContextCorrecta.html new file mode 100755 index 0000000000000000000000000000000000000000..58bdc89d10862aadda9e9fa1ad1b11bc7cbcd2e6 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/FunctionContextCorrecta.html @@ -0,0 +1,46 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <form> + <input type="button" id="testCustomType" value="TestCustomType"> + <input type="button" id="terpButton" value="TerpButton"> + <input type="button" id="checkState" value="CheckState"> + </form> + <div id="displayArea"></div> + + <script> + function displayMessage(message) { + document.getElementById("displayArea").innerHTML = message; + } + + function ButtonState() { + var self = this; /* instead of self we could have used that */ + self.clicked = false; + self.setClicked = function() { self.clicked = true; alert(`Button Selected: ${self.clicked}`);}; + self.getClicked = function() { return self.clicked; }; + } + + document.getElementById("testCustomType").addEventListener("click", function() { + const buttonState = new ButtonState(); + let output = `Initial Button State: ${buttonState.getClicked()}<br>`; + buttonState.setClicked(); + output += `After State Change: ${buttonState.getClicked()}<br>`; + displayMessage(output); + }); + + const terpButtonState = new ButtonState(); + /* Using above custom type to keep track of click state */ + document.getElementById("terpButton").addEventListener("click", terpButtonState.setClicked); + + /* displaying state of above ButtonState */ + document.getElementById("checkState").addEventListener("click", function() { + displayMessage("terpButtonState.getClicked(): " + terpButtonState.getClicked()); + }); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/FunctionContextCorrectb.html b/codeExamples/week1/EventsJSClassesCode/FunctionContextCorrectb.html new file mode 100755 index 0000000000000000000000000000000000000000..bc38ecdc1b9266376e613247bb9284afa41270e2 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/FunctionContextCorrectb.html @@ -0,0 +1,47 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <form> + <input type="button" id="testCustomType" value="TestCustomType"> + <input type="button" id="terpButton" value="TerpButton"> + <input type="button" id="checkState" value="CheckState"> + </form> + <div id="displayArea"></div> + + <script> + function displayMessage(message) { + document.getElementById("displayArea").innerHTML = message; + } + + function ButtonState() { + this.clicked = false; + /* Arrow functions do not have their own this reference; they remember */ + /* this parameter at the point they are defined */ + this.setClicked = () => { this.clicked = true; alert(`Button Selected: ${this.clicked}`);}; + this.getClicked = () => { return this.clicked; }; + } + + document.getElementById("testCustomType").addEventListener("click", function() { + const buttonState = new ButtonState(); + let output = `Initial Button State: ${buttonState.getClicked()}<br>`; + buttonState.setClicked(); + output += `After State Change: ${buttonState.getClicked()}<br>`; + displayMessage(output); + }); + + const terpButtonState = new ButtonState(); + /* Using above custom type to keep track of click state */ + document.getElementById("terpButton").addEventListener("click", terpButtonState.setClicked); + + /* displaying state of above ButtonState */ + document.getElementById("checkState").addEventListener("click", function() { + displayMessage("terpButtonState.getClicked(): " + terpButtonState.getClicked()); + }); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/FunctionContextCorrectc.html b/codeExamples/week1/EventsJSClassesCode/FunctionContextCorrectc.html new file mode 100755 index 0000000000000000000000000000000000000000..19a58de5101cd3048cc34eb350eea0e61d2c97f6 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/FunctionContextCorrectc.html @@ -0,0 +1,47 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <form> + <input type="button" id="testCustomType" value="TestCustomType"> + <input type="button" id="terpButton" value="TerpButton"> + <input type="button" id="checkState" value="CheckState"> + </form> + <div id="displayArea"></div> + + <script> + function displayMessage(message) { + document.getElementById("displayArea").innerHTML = message; + } + + function ButtonState() { + this.clicked = false; + this.setClicked = function() { this.clicked = true; alert(`Button Selected: ${this.clicked}`);}; + this.getClicked = function() { return this.clicked; }; + } + + document.getElementById("testCustomType").addEventListener("click", function() { + const buttonState = new ButtonState(); + let output = `Initial Button State: ${buttonState.getClicked()}<br>`; + buttonState.setClicked(); + output += `After State Change: ${buttonState.getClicked()}<br>`; + displayMessage(output); + }); + + const terpButtonState = new ButtonState(); + /* Using above custom type to keep track of click state */ + /* Using bind to define object to use */ + const setClickedBound = terpButtonState.setClicked.bind(terpButtonState); + document.getElementById("terpButton").addEventListener("click", setClickedBound); + + /* displaying state of above ButtonState */ + document.getElementById("checkState").addEventListener("click", function() { + displayMessage("terpButtonState.getClicked(): " + terpButtonState.getClicked()); + }); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/FunctionContextIncorrect.html b/codeExamples/week1/EventsJSClassesCode/FunctionContextIncorrect.html new file mode 100755 index 0000000000000000000000000000000000000000..d0dc767fb8566d4dcb404f23ceaf9b94c32a670a --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/FunctionContextIncorrect.html @@ -0,0 +1,47 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <form> + <input type="button" id="testCustomType" value="TestCustomType"> + <input type="button" id="terpButton" value="TerpButton"> + <input type="button" id="checkState" value="CheckState"> + </form> + <div id="displayArea"></div> + + <script> + function displayMessage(message) { + document.getElementById("displayArea").innerHTML = message; + } + + function ButtonState() { + this.clicked = false; + this.setClicked = function() { this.clicked = true; alert(`Button Selected: ${this.clicked}`);}; + this.getClicked = function() { return this.clicked; }; + } + + document.getElementById("testCustomType").addEventListener("click", function(e) { + console.log(e.target) + console.log(this) + const buttonState = new ButtonState(); + let output = `Initial Button State: ${buttonState.getClicked()}<br>`; + buttonState.setClicked(); + output += `After State Change: ${buttonState.getClicked()}<br>`; + displayMessage(output); + }); + + const terpButtonState = new ButtonState(); + /* Using above custom type to keep track of click state */ + document.getElementById("terpButton").addEventListener("click", terpButtonState.setClicked); + + /* displaying state of above ButtonState */ + document.getElementById("checkState").addEventListener("click", function() { + displayMessage("terpButtonState.getClicked(): " + terpButtonState.getClicked()); + }); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/Generator1.html b/codeExamples/week1/EventsJSClassesCode/Generator1.html new file mode 100755 index 0000000000000000000000000000000000000000..00d44fe2e41551908ebef57e7c0ed77345523dce --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/Generator1.html @@ -0,0 +1,32 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + function *numGenerator() { + document.writeln("In generator<br>"); + yield 10; + yield 20; + // return "Really Done"; /* What if you comment this out? *? + } + + let myGen = numGenerator(); + document.writeln("After creating generator<br>"); + + let entry = myGen.next(); + document.writeln(entry.value + ", " + entry.done + "<br>"); + + entry = myGen.next(); + document.writeln(entry.value + ", " + entry.done + "<br>"); + + entry = myGen.next(); + document.writeln(entry.value + ", " + entry.done + "<br>"); + + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/Generator2.html b/codeExamples/week1/EventsJSClassesCode/Generator2.html new file mode 100755 index 0000000000000000000000000000000000000000..a219e6785e41a083cc778d34111d46836d15f586 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/Generator2.html @@ -0,0 +1,30 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + function *oddNumGenerator(max) { + for (let i = 1; i <= max; i += 2) { + yield i; + } + } + + let myGen = oddNumGenerator(10); + + let entry = myGen.next(); + document.writeln(entry.value + ", " + entry.done + "<br>"); + + entry = myGen.next(); + document.writeln(entry.value + ", " + entry.done + "<br>"); + + entry = myGen.next(); + document.writeln(entry.value + ", " + entry.done + "<br>"); + + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/GeneratorInClass.html b/codeExamples/week1/EventsJSClassesCode/GeneratorInClass.html new file mode 100755 index 0000000000000000000000000000000000000000..0f5d1462eee796e1d4b02617c642ad381d1df6f0 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/GeneratorInClass.html @@ -0,0 +1,46 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + class SummerCourse { + constructor(name, credits) { + this.name = name; + this.credits = credits; + this.headTA = "Mary"; + this.grader = "Peter"; + } + + toString() { + return `${this.name}, ${this.credits}`; + } + + * taGenerator() { + document.writeln("Beginning of generator<br>"); + yield this.headTA; + yield this.grader; + } + + } + + let course = new SummerCourse("cmsc111", 4); + document.writeln(course + "<br>"); + + let generator = course.taGenerator(); + let ta = generator.next(); + document.writeln(ta.value + ", " + ta.done + "<br>"); + + ta = generator.next(); + document.writeln(ta.value + ", " + ta.done + "<br>"); + + ta = generator.next(); + document.writeln(ta.value + ", " + ta.done + "<br>"); + + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/ImmediatelyInvokedFunctionExpression.html b/codeExamples/week1/EventsJSClassesCode/ImmediatelyInvokedFunctionExpression.html new file mode 100755 index 0000000000000000000000000000000000000000..cb51ad464bfdca421db6969adee9f3eb2169b333 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/ImmediatelyInvokedFunctionExpression.html @@ -0,0 +1,20 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <script> + /* Immediately Invoked Function Expression (IIFE) */ + + /* Placing the function expression within parenthesis */ + document.writeln("IIFE<br>"); + (function (x, y) { + document.writeln(x * y); + } (4, 6)); + document.writeln("End of IIFE<br>"); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/Iterable1.html b/codeExamples/week1/EventsJSClassesCode/Iterable1.html new file mode 100755 index 0000000000000000000000000000000000000000..f7bb8be26f2c1ffbf1a2f28d19b06eddff8c5f71 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/Iterable1.html @@ -0,0 +1,24 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + let message = "Fear the turtle"; + for (let char of message) { + document.writeln(char + "<br>"); + } + + // Accessing the iterator + document.writeln("Accessing iterator<br>"); + let strIterator = message[Symbol.iterator](); + document.writeln(strIterator.next().value); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/Iterable2.html b/codeExamples/week1/EventsJSClassesCode/Iterable2.html new file mode 100755 index 0000000000000000000000000000000000000000..33842204427cfc0206ce5979581359fdf35e4f08 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/Iterable2.html @@ -0,0 +1,38 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + class SummerCourse { + constructor(name, credits) { + this.name = name; + this.credits = credits; + this.headTA = "Mary"; + this.grader = "Peter"; + } + + toString() { + return `${this.name}, ${this.credits}`; + } + + * [Symbol.iterator]() { + yield this.headTA; + yield this.grader; + } + + } + + let course = new SummerCourse("psyc200", 3); + document.writeln(course + "<br>"); + + for (let ta of course) { + document.writeln(ta + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/MethodDefinitions.html b/codeExamples/week1/EventsJSClassesCode/MethodDefinitions.html new file mode 100755 index 0000000000000000000000000000000000000000..0c1fc1a10cd9d7428092054bcf3d9de41fa5097b --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/MethodDefinitions.html @@ -0,0 +1,29 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + let doctor = { + printSpecialty: function() { + document.writeln("heart<br>"); + }, + + /* not using function */ + printDailySchedule(patients, minutes) { + document.writeln("Total time: " + patients * minutes + "<br>"); + } + } + + doctor.printSpecialty(); + doctor.printDailySchedule(10, 20); + + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/ObjectMethods.html b/codeExamples/week1/EventsJSClassesCode/ObjectMethods.html new file mode 100755 index 0000000000000000000000000000000000000000..7318b9c29a009f30d8b1a522d09663c3965cbe70 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/ObjectMethods.html @@ -0,0 +1,33 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + let personsInfo = { name: "Bob", age:24 }; + let personsCourses = { course1: "ENGL101", course2: "PSYC100"}; + let combined = Object.assign(personsInfo, personsCourses); + + /* Notice use of for in */ + for (let key in combined) { + document.writeln(key + ": " + combined[key] + "<br>"); + } + + let student1 = { name: "Tom" }; + let student2 = { name: "Mary" }; + let student3 = { name: "Tom" }; + + document.writeln("Object.is(NaN, NaN): " + Object.is(NaN, NaN) + "<br>"); + document.writeln("Object.is(student1, student2): " + Object.is(student1, student2) + "<br>"); + document.writeln("Object.is(student1, student3): " + Object.is(student1, student3) + "<br>"); + document.writeln("Object.is(student1, student1): " + Object.is(student1, student1) + "<br>"); + + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/Private.html b/codeExamples/week1/EventsJSClassesCode/Private.html new file mode 100755 index 0000000000000000000000000000000000000000..b9ab6f221ec04f20912227892f1b512916e3be4b --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/Private.html @@ -0,0 +1,58 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + /* We need to keep these WeakMaps hidden */ + const _name = new WeakMap(); + const _age = new WeakMap(); + + class Student { + constructor(name, age) { + _name.set(this, name); + _age.set(this, age); + } + + toString() { + return _name.get(this) + " " + _age.get(this); + } + + getName() { + return _name.get(this); + } + + getAge() { + return _age.get(this); + } + + static getCollegeName() { + return "UMCP"; + } + } + + main(); + + function main() { + let s1 = new Student("Charles", 20); + let s2 = new Student("Elizabeth", 30); + + document.writeln(s1 + "<br>"); + document.writeln(s2 + "<br>"); + + document.writeln("College Name: " + Student.getCollegeName() + "<br>"); + document.writeln("Student's name: " + s1.getName() + "<br>"); + + document.writeln(_name); + + /* Student("Kyle", 40); */ /* Check console when commented out */ + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/SetMethods.html b/codeExamples/week1/EventsJSClassesCode/SetMethods.html new file mode 100755 index 0000000000000000000000000000000000000000..8072367a8916b325cc5a6536c6b39adf58f119a7 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/SetMethods.html @@ -0,0 +1,37 @@ +<!doctype html> +<html lang="en"> + <head> + <title>Example</title> + <meta charset="utf-8" /> + </head> + + <body> + <script> + const tas106 = ["John", "Mary", "Laura", "Kelly", "Bob"]; + const tas131 = ["Mary", "Rose", "Bob"]; + + /* Creating set out of array */ + const set106 = new Set(tas106); + for (let elem of set106) { + document.writeln(elem); + } + const set131 = new Set(tas131); + + /* Set union using spread operator to create new array */ + const allTAs = new Set([...set106, ...set131]); + document.writeln("<br>Union (allTAs)<br>"); + for (let elem of allTAs) { + document.writeln(elem + "<br>"); + } + + /* Intersection */ + const inBothCourses = new Set([...set131].filter(ta131 => set106.has(ta131))); + document.writeln("Intersection: " + [...inBothCourses].join() + "<br>"); + + /* Difference */ + document.writeln("106tas that are not 131tas<br>"); + const difference = new Set([...set106].filter(ta106 => !set131.has(ta106))); + document.writeln("Difference: " + [...difference].join() + "<br>"); + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/Spread.html b/codeExamples/week1/EventsJSClassesCode/Spread.html new file mode 100755 index 0000000000000000000000000000000000000000..909f31f3e7f9c357991c52fe8c8d0870954d7e5d --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/Spread.html @@ -0,0 +1,30 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + let courses = new Map(); + courses.set("cmsc122", 3); + courses.set("cmsc216", 4); + + for (let entry of courses) { + document.writeln(entry + "<br>"); + } + + document.writeln("After converting to array<br>"); + let arrayCourses = [...courses]; + for (let i = 0; i < arrayCourses.length; i++) { + document.writeln("entry: " + i + "-->", arrayCourses[i] + "<br>"); + } + + + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/EventsJSClassesCode/Subclass.html b/codeExamples/week1/EventsJSClassesCode/Subclass.html new file mode 100755 index 0000000000000000000000000000000000000000..8411236a3c6c42fbd0e86f38f525a522a2dfa8f5 --- /dev/null +++ b/codeExamples/week1/EventsJSClassesCode/Subclass.html @@ -0,0 +1,52 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + class Student { + constructor(name, age) { + this.name = name; + this.age = age; + } + + toString() { + return this.name + " " + this.age; + } + + getName() { + return this.name; + } + + static getCollegeName() { + return "UMCP"; + } + } + + class StudentAthlete extends Student { + constructor(name, age, sport) { + super(name, age); + this.sport = sport; + } + + toString() { + return super.toString() + " " + this.sport; + } + } + main(); + + function main() { + let athlete1 = new StudentAthlete("Robert", 578, "Programming"); + + document.writeln("Athlete: " + athlete1 + "<br>"); + document.writeln("College: " + StudentAthlete.getCollegeName() + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/AddingProperties.html b/codeExamples/week1/JSObjectsCode/AddingProperties.html new file mode 100755 index 0000000000000000000000000000000000000000..5ddc6453ea78831132afe9dd8fd2fb785e5d6253 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/AddingProperties.html @@ -0,0 +1,36 @@ +<!doctype html> +<html> + <head> + <meta charset="utf-8" /> + <title>Adding Properties</title> + </head> + + <body> + <script> + "use strict"; + + main(); + + function main() { + var sale = new Object(); + + /* Reading the items, number of items */ + var wantAnotherItem, item, numberOfItems; + + do { + item = prompt("Enter name of item you want to buy."); + numberOfItems = prompt("Enter number of items you want to buy."); + sale[item] = numberOfItems; + wantAnotherItem = window.confirm("Do you want to buy another item?"); + } while (wantAnotherItem); + + /* Report about bought items */ + var report = "Items bought\n"; + for (var propertyName in sale) { + report += propertyName + "-->" + sale[propertyName] + "\n"; + } + alert(report); + } + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/ConstructorFunction.html b/codeExamples/week1/JSObjectsCode/ConstructorFunction.html new file mode 100755 index 0000000000000000000000000000000000000000..a54bfa81e17f93f4b1f7b7d68be44984730567ae --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/ConstructorFunction.html @@ -0,0 +1,33 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<html> +<body> + <script> + main(); + + function main() { + var comp1 = new Computer("PC", 30); + var comp2 = new Computer("Mac", 50); + document.writeln("Comp1 model: " + comp1.model + "<br>"); + document.writeln("Comp1 memory: " + comp1.getMemory() + "<br>"); + comp1.setMemory(100); + document.writeln("Comp1 memory: " + comp1.memory + "<br>"); + comp1.monitor = "hd"; /* Does not affect comp2 */ + } + + /* Constructor function */ + function Computer(modelIn, memoryIn) { + this.model = modelIn; + this.memory = memoryIn; + this.getMemory = function() { return this.memory; }; /* we need this.memory */ + this.setMemory = function(memoryValue) { this.memory = memoryValue; } + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/ConstructorPattern.html b/codeExamples/week1/JSObjectsCode/ConstructorPattern.html new file mode 100755 index 0000000000000000000000000000000000000000..49857a190d66531af8c1974c8bf9c5373e029646 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/ConstructorPattern.html @@ -0,0 +1,37 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + main(); + + function main() { + var s1 = new Singer("Psy", "South Korea"); + s1.info(); + document.writeln("Name: " + s1.name + "<br>"); + + var s2 = new Singer("Noolio", "AVW"); + s2.info(); + + /* Calling as function, not constructor */ + Singer("MCNerdson", "CSCI"); + info(); // window.info(); + document.writeln("window.name: " + window.name + "<br>"); + } + + function Singer(name, mainLocation) { // Convention to use capital S + this.name = name; + this.mainLocation = mainLocation; + this.info = function() { + document.writeln("Name: " + this.name); + document.writeln(", MainLocation: " + this.mainLocation + "<br />"); + }; + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/DefaultPattern.html b/codeExamples/week1/JSObjectsCode/DefaultPattern.html new file mode 100755 index 0000000000000000000000000000000000000000..5f3a936e12591ccb9b79806abe54e2f6f40e693b --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/DefaultPattern.html @@ -0,0 +1,44 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + + /* constructor function */ + function Student(name, credits, courses) { + this.name = name; + this.credits = credits; + this.courses = courses; + } + + /* Prototype for all objects created by the Student constructor function */ + Student.prototype = { + constructor: Student, /* Student is the constructor function that creates the object's prototype */ + college: "UMCP", + info: function() { + document.writeln("Name: " + this.name); + document.writeln(", Credits: " + this.credits); + document.writeln(", Courses: " + this.courses + " "); + document.writeln(", College: " + this.college + "<br />"); + } + }; + + main(); + + function main() { + var s1 = new Student("Kelly", 15, [414, 420]); + s1.info(); + s1.courses[2] = [830]; + s1.info(); + + var s2 = new Student("Peter", 12, [314, 320]); + s2.info(); + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/FuncApplyCallBind.html b/codeExamples/week1/JSObjectsCode/FuncApplyCallBind.html new file mode 100755 index 0000000000000000000000000000000000000000..e1b5ab9e2cf2605a040d8eac24fc366c483e7893 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/FuncApplyCallBind.html @@ -0,0 +1,56 @@ +<!doctype html> +<html> +<head> + <meta charset="UTF-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + window.terpConstant = 100; + + main(); + + function main() { + document.writeln("product(1, 2): " + product(1, 2) + "<br>"); + document.writeln("applyArguments(3, 4): " + applyArguments(3, 4) + "<br>"); + document.writeln("applyArray(2, 3):" + applyArray(2, 3) + "<br>"); + document.writeln("applyAndObject(3, 5): " + applyAndObject(3, 5) + "<br>"); + document.writeln("callExample(6, 5): " + callExample(6, 5) + "<br>"); + + document.writeln("bindExample(): "); + bindExample(); + } + + function product(x, y) { + return x * y * this.terpConstant; + } + + function applyArguments(x, y) { + return product.apply(this, arguments); + } + + function applyArray(x, y) { + return product.apply(this, [x, y]); + } + + function applyAndObject(x, y) { + var obj = new Object(); + obj.terpConstant = 1000; + return product.apply(obj, [x, y]); + } + + function callExample(x, y) { + return product.call(this, x, y); + } + + function bindExample() { + var obj = new Object(); + obj.terpConstant = 9; + + var productObj = product.bind(obj); + document.writeln(productObj(2, 5)); + } + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/FuncArguments.html b/codeExamples/week1/JSObjectsCode/FuncArguments.html new file mode 100755 index 0000000000000000000000000000000000000000..dfd1c0da5ef1a33cfa284d49e2d3841a83f27f07 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/FuncArguments.html @@ -0,0 +1,26 @@ +<!doctype html> +<html> +<head> + <meta charset="UTF-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + main(); + + function processData(x, y) { + document.writeln(arguments.length); + document.writeln(arguments[0]); + document.writeln(arguments[1] + "<hr>"); + + if (x !== 0) { + arguments.callee(--x, --y); /* recursive call */ + } + } + function main() { + processData(3, 4); + } + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/FuncLength.html b/codeExamples/week1/JSObjectsCode/FuncLength.html new file mode 100755 index 0000000000000000000000000000000000000000..d0217b3724a6d1c9eef99d1078be2fc19df12869 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/FuncLength.html @@ -0,0 +1,29 @@ +<!doctype html> +<html> +<head> + <meta charset="UTF-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + main(); + + function main() { + document.writeln("generateResults.length: " + generateResults.length + "<br>"); + document.writeln("moreResults.length: " + moreResults.length + "<br>"); + document.writeln("generateResults.toString(): " + generateResults.toString() + "<br>"); + document.writeln("generateResults.valueOf(): " + generateResults.valueOf() + "<br>"); + + } + + function generateResults(x) { + document.writeln(x); + } + + function moreResults(x, y) { + document.writeln(x, y); + } + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/FuncThis.html b/codeExamples/week1/JSObjectsCode/FuncThis.html new file mode 100755 index 0000000000000000000000000000000000000000..daced67e64f828e353c2f92ae397ba466927dd69 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/FuncThis.html @@ -0,0 +1,32 @@ +<!doctype html> +<html> +<head> + <meta charset="UTF-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + window.singer = "Psy"; + var obj = new Object(); + obj.singer = "NP"; + + main(); + + function main() { + singerInfo(); + document.writeln("Using object<br />"); + + var obj = new Object(); + obj.singer = "Coolio"; + obj.singerInfo = singerInfo; + obj.singerInfo(); + } + + function singerInfo() { + document.writeln(this.singer + "<br />"); + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/Inheritance.html b/codeExamples/week1/JSObjectsCode/Inheritance.html new file mode 100755 index 0000000000000000000000000000000000000000..1298502790fa56840104ca0e212ed7d965deaa82 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/Inheritance.html @@ -0,0 +1,53 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + + /* constructor function */ + function Student(name, credits, courses) { + this.name = name; + this.credits = credits; + this.courses = courses; + } + + Student.prototype = { + constructor: Student, + college: "UMCP", + info: function() { + document.writeln("Name: " + this.name); + document.writeln(", Credits: " + this.credits); + document.writeln(", Courses: " + this.courses + " "); + document.writeln(", College: " + this.college + "<br />"); + } + }; + + function GradStudent(name, credits, courses, advisor) { + /* Calls super class constructor */ + Student.call(this, name, credits, courses); + + this.advisor = advisor; + } + + + GradStudent.prototype = new Student(); + GradStudent.prototype.constructor = GradStudent; + GradStudent.prototype.getAdvisor = function() { return this.advisor; } + + + main(); + function main() { + var gs1 = new GradStudent("Kelly", 15, [414, 420], "Dr. Smith"); + gs1.info(); + document.writeln(gs1.getAdvisor() + "<br>"); + document.writeln("Name: " + gs1.name + "<br>"); + document.writeln("College: " + gs1.college + "<br>"); + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/JSONExample.html b/codeExamples/week1/JSObjectsCode/JSONExample.html new file mode 100755 index 0000000000000000000000000000000000000000..0111593fdf90746dfb87eea0da21f06429c21174 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/JSONExample.html @@ -0,0 +1,31 @@ +<!doctype html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + var obj = { + name: "Mary", + age: 45, + salary: 20000.00 + }; + + var str = JSON.stringify(obj); + document.writeln(str); + + var new_obj = JSON.parse(str); + document.writeln("<h2>After Parsing Object</h2>") + for (var prop in new_obj) { + document.writeln(prop + "--> " + new_obj[prop] + "<br>"); + } + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/ObjectCreate.html b/codeExamples/week1/JSObjectsCode/ObjectCreate.html new file mode 100755 index 0000000000000000000000000000000000000000..fd2a561cb4e8317e1b3a026ccdc590ac681ff02f --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/ObjectCreate.html @@ -0,0 +1,66 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + main(); + + function main() { + // Generic dessert + var dessert = { + minimumCalories: 100, + displayDessert: function() { + document.writeln(this.name + ", " + this.calories + "<br>"); + } + }; + + document.writeln("<h2>dessert Properties</h2>"); + document.writeln("toString: " + dessert.toString() + "<br>"); + var propertiesArray = getAllProperties(dessert); + for (var i = 0; i < propertiesArray.length; i++) { + document.writeln(propertiesArray[i] + "<br>"); + } + if (Object.prototype.isPrototypeOf(dessert)) { + document.writeln("Object.prototype is prototype of dessert<br>"); + } + + // Creating new type (cheesecake) + var cheesecake = Object.create(dessert); + cheesecake.name = "cheesecake"; + cheesecake.calories = 750; + cheesecake.displayDessert(); + + document.writeln("<h2>Cheesecake Properties</h2>"); + var propertiesArray = getAllProperties(cheesecake); + for (var i = 0; i < propertiesArray.length; i++) { + document.writeln(propertiesArray[i] + "<br>"); + } + + if (dessert.isPrototypeOf(cheesecake)) { + document.writeln("dessert is prototype of cheesecake<br>"); + } + if (Object.prototype.isPrototypeOf(cheesecake)) { + document.writeln("Object.prototype is prototype of cheesecake<br>"); + } + } + + /* Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects */ + function getAllProperties(src){ + var currObj, answer = []; + + /* Traversing the prototype chain */ + currObj = src; + while (currObj !== null) { + answer = answer.concat(Object.getOwnPropertyNames(currObj)); + currObj = Object.getPrototypeOf(currObj); + } + + return answer; + } + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/Objects.html b/codeExamples/week1/JSObjectsCode/Objects.html new file mode 100755 index 0000000000000000000000000000000000000000..6ebfeadc1b0d45d6903e8c0eb693669ac868da50 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/Objects.html @@ -0,0 +1,67 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + main(); + + function main() { + /* Alternatives for creating an empty object */ + var emptyObject1 = new Object(); + var emptyObject2 = new Object(undefined); + var emptyObject3 = new Object(null); + + /* Boolean Object alternative */ + var booleanObject1 = new Object(true); + var booleanObject2 = new Boolean(true); + + /* Using Object constructor for person object */ + var person1 = new Object(); + /* Adding properties */ + + person1.name = "John"; + person1.age = 45; + person1.school = umcpSchool; + printPerson(person1); + + /* Using object initializer/literal notation */ + var person2 = { + name: "Mary", + age: 30, + school: umcpSchool, + bestFriend: person1 + }; + + printPerson(person2); + + var exam = { + semester: "fall", + "difficulty-level": 10, + 2: "midterm2" + + }; + + // NOT VALID alert("First form: " + exam.difficulty-level); + document.writeln("difficulty-level: " + exam["difficulty-level"] + "<br>"); + document.writeln("exam[2]: " + exam[2] + "<br>"); + } + + 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> \ No newline at end of file diff --git a/codeExamples/week1/JSObjectsCode/PrototypePattern.html b/codeExamples/week1/JSObjectsCode/PrototypePattern.html new file mode 100755 index 0000000000000000000000000000000000000000..58d7392750520a4a39125f08c95ef5649b0e3098 --- /dev/null +++ b/codeExamples/week1/JSObjectsCode/PrototypePattern.html @@ -0,0 +1,37 @@ +<!doctype html> +<html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + + /* constructor function */ + function Student() { + } + + Student.prototype.name = "Jose"; + Student.prototype.credits = 15; + Student.prototype.courses =[424, 430]; + Student.prototype.info = function() { + document.writeln("Name: " + this.name); + document.writeln(", Credits: " + this.credits); + document.writeln(", Courses: " + this.courses + "<br />"); + }; + + main(); + + function main() { + var s1 = new Student(); + s1.info(); + s1.courses[2] = 414; + + var s2 = new Student(); + s2.info(); // Notice that 414 has also been added here + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/DrawingPointer.html b/codeExamples/week1/ObjsAPISCode/DrawingPointer.html new file mode 100755 index 0000000000000000000000000000000000000000..25a799abbd21a001a3a9a3bc18378ab902a0b544 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/DrawingPointer.html @@ -0,0 +1,51 @@ +<!doctype html> +<html> + <head> + <meta charset="utf-8" /> + <title>Mouse Drawing</title> + </head> + + <body> + <canvas id="canvas" width="400" height="300"></canvas> + + <script> + "use strict"; + + var color = "red"; + var sideLength = 5; + + main(); + + function main() { + document.onmousemove = processMousePosition; + document.onkeypress = changeColor; + document.writeln("<p>"); + document.writeln("<strong>Move the mouse in the above area."); + document.writeln("Press enter to change to erase mode;"); + document.writeln("Press enter again to change to drawing mode</strong>"); + document.writeln("</p>"); + } + + function processMousePosition(evt) { + draw(evt.pageX, evt.pageY); + } + + function changeColor() { + if (color === "red") { + color = "white"; + sideLength = 500; + } else { + color = "red"; + sideLength = 5; + } + } + + function draw(xPos, yPos) { + var context = document.getElementById("canvas").getContext("2d"); + + context.fillStyle = color; + context.fillRect(xPos, yPos, sideLength, sideLength); + } + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/Errors1.html b/codeExamples/week1/ObjsAPISCode/Errors1.html new file mode 100755 index 0000000000000000000000000000000000000000..6ceb17e9b99b165443934419bafadbd914e13207 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/Errors1.html @@ -0,0 +1,24 @@ +<!doctype html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + try { + alert("About to access method"); + window.terps(); + } catch(error) { + alert("Problem: " + error.message); + } + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/Errors2.html b/codeExamples/week1/ObjsAPISCode/Errors2.html new file mode 100755 index 0000000000000000000000000000000000000000..a2bab6a2c7d68cd1380c37c513149a6efd15a247 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/Errors2.html @@ -0,0 +1,47 @@ +<!doctype html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + try { + var option = prompt("Enter 1, 2, 3 for error case"); + + switch (option) { + case "1": + var x = new Array(-4); + break; + case "2": + var x = y; + break; + case "3": + var k = 234; + var w = k.charAt(0); + break; + } + } catch(error) { + var messageDes; + + if (error instanceof RangeError) { + messageDes = "Range: "; + } else if (error instanceof ReferenceError) { + messageDes = "Reference: "; + } else if (error instanceof TypeError) { + messageDes = "Type: " + } else { + messageDes = "Other: "; + } + + alert(messageDes + error.message); + } + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/Errors3.html b/codeExamples/week1/ObjsAPISCode/Errors3.html new file mode 100755 index 0000000000000000000000000000000000000000..78b22c33c24056f932ba9553d744ddaa3d40702e --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/Errors3.html @@ -0,0 +1,33 @@ +<!doctype html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + function InvalidDataError(message) { + this.name = "InvalidDataError"; + this.message = message; + } + InvalidDataError.prototype = new Error(); + + main(); + + function main() { + try { + var value = Number(prompt("Enter positive (or 0) value")); + if (value < 0) { + throw new InvalidDataError("positive value expected"); + } else { + alert("Square Root: " + Math.sqrt(value)); + } + } catch(error) { + alert(error.message); + } + } + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/ExtensibleSealed.html b/codeExamples/week1/ObjsAPISCode/ExtensibleSealed.html new file mode 100755 index 0000000000000000000000000000000000000000..39a90c60b5fa5603eefc62687ba42721047c087d --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/ExtensibleSealed.html @@ -0,0 +1,45 @@ +<!doctype html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + var student = new Object(); + student.name = "Rose"; + Object.preventExtensions(student); + + // NOT Allowed student.gpa = 3.2; + student.name = "Mark"; + document.writeln("<br />gpa: " + student.gpa); + document.writeln("<br />name: " + student.name); + + /* We can delete properties */ + delete student.name; + document.writeln("<br />name (after deleting): " + student.name); + + /* Sealing the object */ + var game = new Object(); + game.name = "SuperTetris"; + Object.seal(game); + + /* Ignored */ + /* NOT Allowed game.year = 2000; */ + /* NOT Allowed delete game.name; */ + + 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/codeExamples/week1/ObjsAPISCode/FileReading/FileReadingImage.html b/codeExamples/week1/ObjsAPISCode/FileReading/FileReadingImage.html new file mode 100755 index 0000000000000000000000000000000000000000..3ec7e2a223a2b9879e462f9792423c133ca302a6 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/FileReading/FileReadingImage.html @@ -0,0 +1,38 @@ +<!doctype html> +<html> + <head> + <meta charset="UTF-8" /> + <title>JavaScript Program Template</title> + </head> + + <body onload="main()"> + <div> + <input type="file" id="fileElement"> + <pre id="displayArea"> + </pre> + </div> + + <script> + "use strict"; + + function main() { + document.getElementById("fileElement").onchange = loadData; + } + + function loadData(e) { + var file = document.getElementById("fileElement").files[0]; + var reader = new FileReader(); + + reader.onload = function(event) { + var img = new Image(); + + img.src = reader.result; + document.getElementById("displayArea").appendChild(img); + }; + + reader.readAsDataURL(file); + } + + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/FileReading/FileReadingText.html b/codeExamples/week1/ObjsAPISCode/FileReading/FileReadingText.html new file mode 100755 index 0000000000000000000000000000000000000000..c466ce60cda33d9fa7a4212cbaf7492bfd244a57 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/FileReading/FileReadingText.html @@ -0,0 +1,35 @@ +<!doctype html> +<html> + <head> + <meta charset="UTF-8" /> + <title>JavaScript Program Template</title> + </head> + + <body onload="main()"> + <div> + <input type="file" id="fileElement"> + <pre id="displayArea"> + </pre> + </div> + + <script> + "use strict"; + + function main() { + document.getElementById("fileElement").onchange = loadData; + } + + function loadData(e) { + var file = document.getElementById("fileElement").files[0]; + var reader = new FileReader(); + + reader.onload = function(event) { + document.getElementById("displayArea").innerHTML = reader.result; + }; + + reader.readAsText(file); + } + + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/FileReading/data.txt b/codeExamples/week1/ObjsAPISCode/FileReading/data.txt new file mode 100755 index 0000000000000000000000000000000000000000..6ca778393277bf2808b3a2bfafabe7b7ab438be7 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/FileReading/data.txt @@ -0,0 +1,3 @@ +This is a file +with some +sample data. diff --git a/codeExamples/week1/ObjsAPISCode/FileReading/picture.png b/codeExamples/week1/ObjsAPISCode/FileReading/picture.png new file mode 100755 index 0000000000000000000000000000000000000000..4325e442001d6001bf841ff6b9cc19ae57a5969c Binary files /dev/null and b/codeExamples/week1/ObjsAPISCode/FileReading/picture.png differ diff --git a/codeExamples/week1/ObjsAPISCode/FileReading/studentsInM.jpg b/codeExamples/week1/ObjsAPISCode/FileReading/studentsInM.jpg new file mode 100755 index 0000000000000000000000000000000000000000..b26f15d22966eeb998be7c879e5df15e0e0bc008 Binary files /dev/null and b/codeExamples/week1/ObjsAPISCode/FileReading/studentsInM.jpg differ diff --git a/codeExamples/week1/ObjsAPISCode/Freeze.html b/codeExamples/week1/ObjsAPISCode/Freeze.html new file mode 100755 index 0000000000000000000000000000000000000000..a23b0be833460342041be5592fb9b8dad81163e1 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/Freeze.html @@ -0,0 +1,29 @@ +<!doctype html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + var school = new Object(); + var info; + + school.name = "UMCP"; + school.city = "College Park"; + Object.freeze(school); + + /* NOT Allowed (Generates error) school.mascot = "terp"; */ + /* NOT Allowed (Generates error) school.name = "UMD"; */ + /* NOT Allowed (Generates error) delete school.city; */ + + info = school.name + " " + school.city + " " + school.mascot; + document.writeln(info); + } + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/Geolocation.html b/codeExamples/week1/ObjsAPISCode/Geolocation.html new file mode 100755 index 0000000000000000000000000000000000000000..0febaa612c5a7f1234a1c3bb74c069f56b1c016c --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/Geolocation.html @@ -0,0 +1,32 @@ +<!doctype html> +<html> + <head> + <meta charset="utf-8" /> + <title>Geolocation</title> + </head> + <body> + <script> + if (!navigator.geolocation) { + alert("Geolocation not supported in current browser"); + } else { + navigator.geolocation.getCurrentPosition(success, failure); + } + function success(position) { + var latitude = position.coords.latitude; + var longitude = position.coords.longitude; + document.writeln("Position is: " + latitude + ", " + longitude); + document.writeln("<br />Copy above position in "); + document.writeln("<a href=\"http://maps.google.com/maps\">google maps</a>"); + document.writeln(" to verify location "); + } + function failure(error) { + var errors = { + 1: "Permission denied", + 2: "Position unavailable", + 3: "Request timeout" + }; + alert("Error ocurred: " + errors[error.code]); + } + </script> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/GetterSetter.html b/codeExamples/week1/ObjsAPISCode/GetterSetter.html new file mode 100755 index 0000000000000000000000000000000000000000..6c9eceb2ce8c1d25ed346ac5f940475caefdc893 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/GetterSetter.html @@ -0,0 +1,29 @@ +<!doctype html> +<html> +<head> + <meta charset="UTF-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + var person = { + _firstname: "John", + _age: 35, + get getname() { return this._firstname;}, + get age() { return this._age;}, + set age(age) { return this._age = age;} + }; + + document.writeln(person.getname); + document.writeln(person.age); + person.age = 40; /* To update we assign the value */ + document.writeln(person.age); /* retrieving the value */ + person._age = 100; + document.writeln("<br>Still modifying property: " + person.age) + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/GuessGameWithSound.html b/codeExamples/week1/ObjsAPISCode/GuessGameWithSound.html new file mode 100755 index 0000000000000000000000000000000000000000..137f4b0530e22e0a5858cd4cf6d11fc896c6cb9c --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/GuessGameWithSound.html @@ -0,0 +1,42 @@ +<!doctype html> +<html> + <head> + <meta charset="UTF-8" /> + <title>JavaScript Program Template</title> + </head> + <body> + + <div id="imageBox"> + <img id="myImage" src="YOUR_PLAY_GAME_IMAGE_HERE.png" alt="Status" /> + </div> + + <audio id="mySound"> + <source src="YOUR_SOUND_HERE.mp3" type="audio/mpeg"> + </audio> + + <script> + "use strict"; + + + function displayPhoto(photoToDisplay) { + var imageElement = document.getElementById("myImage"); + imageElement.setAttribute("src", photoToDisplay); + } + + var valueToGuess = Math.floor(2 * Math.random()) + 1; + var guess; + do { + guess = Number(prompt("Enter your guess")); + if (guess == valueToGuess) { + alert("Good Job!!!"); + displayPhoto("YOUR_WINNER_IMAGE_HERE.jpg"); + var myAudio = document.getElementById("mySound"); + myAudio.play(); + } else { + alert("Wrong guess"); + } + } while(valueToGuess !== guess); + </script> + + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/PrivateVarFunctions.html b/codeExamples/week1/ObjsAPISCode/PrivateVarFunctions.html new file mode 100755 index 0000000000000000000000000000000000000000..2893aefa3d48b7ae9b78dc49ade5857e64b9c49c --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/PrivateVarFunctions.html @@ -0,0 +1,54 @@ +<!doctype html> +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + function Student(name, age) { + /* private variable */ + let maxAge = 108; + + this.getName = function() { + return name; + } + + this.getAge = function() { + return age; + } + + this.setAge = function(ageIn) { + if (validAge(ageIn)) { + age = ageIn; + } + }; + + /* Private function. */ + function validAge(ageVal) { + if (ageVal < maxAge) { + return true; + } + return false; + } + } + main(); + + function main() { + let s1 = new Student("Mary", 34); + + document.writeln("name: " + s1.name + "<br>"); + document.writeln("age: " + s1.age + "<br>"); + document.writeln("maxAge: " + s1.maxAge + "<br>"); + + document.writeln("getName: " + s1.getName() + "<br>"); + document.writeln("getAge: " + s1.getAge() + "<br>"); + s1.setAge(40); + document.writeln("getAge (after update): " + s1.getAge() + "<br>"); + } + + </script> +</body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/ThrowDie.html b/codeExamples/week1/ObjsAPISCode/ThrowDie.html new file mode 100755 index 0000000000000000000000000000000000000000..2b35ad57501a292d298a1ace1a9475fa082c8006 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/ThrowDie.html @@ -0,0 +1,56 @@ +<!doctype html> +<html> + <head> + <meta charset="UTF-8" /> + <title>JavaScript Program Template</title> + </head> + <body onload="main()"> + + <span id="imageBox"> + </span> + <span id="imageBox2"> + </span> + <input type="button" id="myButton" value="Roll"> + + <script> + "use strict"; + + var animation; + var times = 5; + var curr = 0; + + function main() { + var myButton = document.getElementById("myButton"); + myButton.onclick = roll; + } + + function roll() { + curr = 0; + animation = setInterval("throwDies()", 1000); + } + + function displayPhoto(photoToDisplay) { + var imageElement = document.getElementById("myImage"); + imageElement.setAttribute("src", photoToDisplay); + } + + function throwDies() { + var dieNumber = Math.floor(6 * Math.random()); + var value = 9856 + dieNumber; + + document.getElementById("imageBox").innerHTML = "&#" + value; + + dieNumber = Math.floor(6 * Math.random()); + value = 9856 + dieNumber; + document.getElementById("imageBox2").innerHTML = "&#" + value; + + curr++; + if (curr == times) { + clearInterval(animation); + } + } + + </script> + + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/ObjsAPISCode/TodoList.html b/codeExamples/week1/ObjsAPISCode/TodoList.html new file mode 100755 index 0000000000000000000000000000000000000000..d6687611b08ad43c4c3356b8b69df43761d06809 --- /dev/null +++ b/codeExamples/week1/ObjsAPISCode/TodoList.html @@ -0,0 +1,34 @@ +<!DOCTYPE html> + <html> + <head> + <meta charset="utf-8"> + <title>Todo List</title> + </head> + <body onload="main()"> + <h1>Todo List</h1> + + <form id="mainForm"> + <!-- Notice the contenteditable attribute --> + <ol id="todoList" contenteditable><li>Add Tasks</li></ol> + <input id="SaveButton" type="button" value="Save"> + </form> + + <script> + function main() { + + var todoList = localStorage.getItem("todoList"); + if (todoList === null) { + todoList = "<li>Add Tasks</li>" + } + document.getElementById("todoList").innerHTML = todoList; + + /* Using anonymous function as listener */ + document.getElementById("SaveButton").onclick = function() { + var todoList = document.getElementById("todoList").innerHTML; + localStorage.setItem("todoList", todoList); + alert("Data saved"); + }; + } + </script> + +</body></html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/NaN.html b/codeExamples/week1/introductionToJavascript-1/NaN.html new file mode 100644 index 0000000000000000000000000000000000000000..c92493c1d7b564d13b7a15b1bc4ab215de8c725d --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/NaN.html @@ -0,0 +1,45 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>NaN</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + var examScore = 84.5; + var name = "Mary Smith"; + + var message = "empty string to number: " + Number("") + "\n"; + message += "examScore is a number: " + !isNaN(examScore) + "\n"; + message += "empty string is not a number: " + isNaN("") + "\n"; + message += "!isNaN(name) is a number: " + !isNaN(name) + "\n"; + message += "!Number.isNaN(name) is a number: " + !Number.isNaN( + name) + "\n"; + message += "NaN == NaN: " + (NaN == NaN) + "\n"; + message += "NaN === NaN: " + (NaN === NaN) + "\n"; + message += "NaN == \"hello\": " + (NaN == "hello") + "\n"; + message += "\"24Hi\" is a number: " + !isNaN("24Hi") + "\n"; + message += "\"-24\" is a number: " + !isNaN("-24") + "\n"; + message += "\"+24\" is a number: " + !isNaN("+24") + "\n"; + message += "\"24Hi\" is a number: " + !Number.isNaN("24Hi") + + " -- strange? \n"; + message += "\"-24\" is a number: " + !Number.isNaN("-24") + "\n"; + message += "\"+24\" is a number: " + !Number.isNaN("+24") + "\n"; + message += "Numerical expression is a number: " + !isNaN(5 + 4) + + "\n"; + message += "String expression is a number: " + !isNaN("5" + "4") + + "\n"; + message += "String expression (2) is a number: " + !isNaN("5 + 4") + + "\n"; + alert(message); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arrayEverySome.html b/codeExamples/week1/introductionToJavascript-1/arrayEverySome.html new file mode 100644 index 0000000000000000000000000000000000000000..032e74f9f590a64d85a8f14f17186149ef70e753 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arrayEverySome.html @@ -0,0 +1,28 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Array every and some method Example</title> +</head> + +<body> + <script> + "use strict"; + + let atLeastOneOdd = [2, 6, 8, 1, 4].some(isOdd); + let allOdd1 = [2, 6, 8, 1, 4].every(isOdd); + let allOdd2 = [1, 3, 5, 9, 7].every(isOdd); + + // index and array are optional + function isOdd(elem, index, array){ + return (elem % 2 === 1); + } + + document.writeln("atLeastOneOdd: " + atLeastOneOdd + "<br>"); + document.writeln("allOdd1: " + allOdd1 + "<br>"); + document.writeln("allOdd2: " + allOdd2 + "<br>"); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arrayFind.html b/codeExamples/week1/introductionToJavascript-1/arrayFind.html new file mode 100644 index 0000000000000000000000000000000000000000..6e1ea5002b6afda87e25f7f500563b1360737586 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arrayFind.html @@ -0,0 +1,22 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Array find method Example</title> +</head> + +<body> + <script> + "use strict"; + + let languages = ["C++", "Fortran", "JavaScript"]; + let found = languages.find(function (e) { + return e.length > 5; + }); + + console.log(found); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arrayFindIndex.html b/codeExamples/week1/introductionToJavascript-1/arrayFindIndex.html new file mode 100644 index 0000000000000000000000000000000000000000..20cf6c3ffac757809b836c0374d5513515398a73 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arrayFindIndex.html @@ -0,0 +1,22 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Array find method Example</title> +</head> + +<body> + <script> + "use strict"; + + let languages = ["C++", "Fortran", "JavaScript"]; + let foundIdx = languages.findIndex(function (e) { + return e.length > 8; + }); + + alert(foundIdx + " " + languages[foundIdx]); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arrayMap.html b/codeExamples/week1/introductionToJavascript-1/arrayMap.html new file mode 100644 index 0000000000000000000000000000000000000000..3af74813d611a122df06c0f99379cc28d8f74f4a --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arrayMap.html @@ -0,0 +1,27 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Array map method Example</title> +</head> + +<body> + <script> + "use strict"; + + var numbers = [1, 4, 9]; + var doubles = numbers.map(function (num) { + return num * 2; + }); + + debugger; + + var triples = numbers.map( n => n * 3); + + document.writeln(doubles + "<br>"); + document.writeln(triples + "<br>"); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arrayMethods.html b/codeExamples/week1/introductionToJavascript-1/arrayMethods.html new file mode 100644 index 0000000000000000000000000000000000000000..5386e2ee0d6d4a7e291580c9821ef35a1a238eb1 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arrayMethods.html @@ -0,0 +1,107 @@ +<!doctype html> +<html> + +<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() { + var languages = ["JavaScript", "Java", "PHP", "Python"]; + document.writeln(languages + "<br>") + document.writeln("Length: " + languages.length + "<br>"); + document.writeln("<br>"); + + languages.push("C"); + document.writeln("After pushing element<br>"); + printArray(languages); + + var retrieved = languages.pop(); + document.writeln("Popped element: " + retrieved + "<br>"); + document.writeln("After popping element<br>"); + printArray(languages); + document.writeln("<br>"); + + var retrieved = languages.shift(); + document.writeln("Shifted element: " + retrieved + "<br>"); + document.writeln("After shifting<br>"); + printArray(languages); + + document.writeln("After unshifting<br>"); + languages.unshift(retrieved); + printArray(languages); + document.writeln("<br>"); + + document.writeln("Finding index of \"Python\": "); + document.writeln(languages.indexOf("Python") + "<br>"); + document.writeln("Finding index of \"C\": "); + document.writeln(languages.indexOf("C") + "<br>"); + document.writeln("<br>"); + + document.writeln("Before removing elements with splice<br>"); + printArray(languages); + // returns removed elements array + var removedElements = languages.splice(1, 2); + document.writeln("After removing elements with splice<br>"); + printArray(languages); + document.writeln("Elements removed<br>"); + printArray(removedElements); + document.writeln("<br>"); + + languages.splice(1, 0, "Go", "C++", "Ruby"); + document.writeln("After adding 3 elements with splice<br>"); + printArray(languages); + document.writeln("<br>"); + document.writeln("slice example<br>"); + var shallowCopy = languages.slice(); + document.writeln("Shallow copy<br>"); + printArray(shallowCopy); + shallowCopy[1] = "Perl"; + printArray(shallowCopy); + printArray(languages); // String is primitives. + document.writeln("<br>"); + + var seasons = ["Fall", "Winter", "Spring", "Summer"]; + seasons.reverse(); + document.writeln("After reversing array<br>"); + printArray(seasons); + document.writeln("<br>"); + + var part1 = [10, 20, 30]; + var part2 = [40, 50, 60]; + var part3 = part1.concat(part2); + document.writeln("After concatenating<br>"); + printArray(part3); + document.writeln("<br>"); + + document.writeln("After fill<br>"); + var filled = new Array(4).fill(100); + printArray(filled); + document.writeln("<br>"); + + document.writeln("Devices<br>"); + var devices = ["Computer", "Clock", "Generator"]; + devices[7] = "Phone"; + devices.forEach(function (elem, index) { + document.writeln("Index: " + index + ", Elem: " + elem + "<br>"); + }); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arraySlice.html b/codeExamples/week1/introductionToJavascript-1/arraySlice.html new file mode 100644 index 0000000000000000000000000000000000000000..8910058c69326db642b52c3669892b898382f630 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arraySlice.html @@ -0,0 +1,130 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Array Slice Example</title> +</head> + +<body> + <script> + "use strict"; + + var arr = new Array(); + arr.push({ + name: 'Maryland' + }); + arr.push({ + name: 'Virginia' + }); + arr.push({ + name: 'Delaware' + }); + + document.writeln("Before modification<br>"); + var sliced = arr.slice(1, 3); // only DE and VA + printArray(arr); + printArray(sliced); + document.writeln("<br>"); + + sliced[0].name = 'Texas'; + + document.writeln("After modification<br>"); + /* note that both arrays have Texas. It's shallow copy */ + printArray(arr); + printArray(sliced); + + + function printArray(data) { + var i; + + for (i = 0; i < data.length; i++) { + document.writeln(data[i].name + " "); + } + document.writeln("<br>"); + } + + function main() { + var languages = ["JavaScript", "Java", "PHP", "Python"]; + document.writeln(languages + "<br>") + document.writeln("Length: " + languages.length + "<br>"); + document.writeln("<br>"); + + languages.push("C"); + document.writeln("After pushing element<br>"); + printArray(languages); + + var retrieved = languages.pop(); + document.writeln("Popped element: " + retrieved + "<br>"); + document.writeln("After popping element<br>"); + printArray(languages); + document.writeln("<br>"); + + var retrieved = languages.shift(); + document.writeln("Shifted element: " + retrieved + "<br>"); + document.writeln("After shifting<br>"); + printArray(languages); + + document.writeln("After unshifting<br>"); + languages.unshift(retrieved); + printArray(languages); + document.writeln("<br>"); + + document.writeln("Finding index of \"Python\": "); + document.writeln(languages.indexOf("Python") + "<br>"); + document.writeln("Finding index of \"C\": "); + document.writeln(languages.indexOf("C") + "<br>"); + document.writeln("<br>"); + + document.writeln("Before removing elements with splice<br>"); + printArray(languages); + // returns removed elements array + var removedElements = languages.splice(1, 2); + document.writeln("After removing elements with splice<br>"); + printArray(languages); + document.writeln("Elements removed<br>"); + printArray(removedElements); + document.writeln("<br>"); + + languages.splice(1, 0, "Go", "C++", "Ruby"); + document.writeln("After adding 3 elements with splice<br>"); + printArray(languages); + document.writeln("<br>"); + document.writeln("slice example<br>"); + var shallowCopy = languages.slice(); + document.writeln("Shallow copy<br>"); + printArray(shallowCopy); + shallowCopy[1] = "Perl"; + printArray(shallowCopy); + printArray(languages); // String is primitives. + document.writeln("<br>"); + + var seasons = ["Fall", "Winter", "Spring", "Summer"]; + seasons.reverse(); + document.writeln("After reversing array<br>"); + printArray(seasons); + document.writeln("<br>"); + + var part1 = [10, 20, 30]; + var part2 = [40, 50, 60]; + var part3 = part1.concat(part2); + document.writeln("After concatenating<br>"); + printArray(part3); + document.writeln("<br>"); + + document.writeln("After fill<br>"); + var filled = new Array(4).fill(100); + printArray(filled); + document.writeln("<br>"); + + document.writeln("Devices<br>"); + var devices = ["Computer", "Clock", "Generator"]; + devices[7] = "Phone"; + devices.forEach(function (elem, index) { + document.writeln("Index: " + index + ", Elem: " + elem + "<br>"); + }); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arraysLengthProp.html b/codeExamples/week1/introductionToJavascript-1/arraysLengthProp.html new file mode 100644 index 0000000000000000000000000000000000000000..3933b15727a4590f1cd13015f444273dfa70c54e --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arraysLengthProp.html @@ -0,0 +1,50 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8"> + <title>Arrays Length Property</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + var languages = ["English", "Spanish", "French"]; + + printArray(languages); + document.writeln("Length: " + languages.length + "<br>"); + + // see what values are used for the elements in the middle + languages[8] = "Italian"; + document.writeln("After adding Italian<br>"); + printArray(languages); + + document.writeln("Keys<br>"); + // 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. + document.writeln(Object.keys(languages) + "<br>"); + document.writeln("Length: " + languages.length + "<br>"); + + languages.length = 2; + document.writeln("After changing length<br>"); + printArray(languages); + + } + + function printArray(data) { + var i; + + for (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/codeExamples/week1/introductionToJavascript-1/arraysOneDim.html b/codeExamples/week1/introductionToJavascript-1/arraysOneDim.html new file mode 100644 index 0000000000000000000000000000000000000000..6e0d98eeff978a5d67c396c7af91cf583bce893e --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arraysOneDim.html @@ -0,0 +1,48 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8"> + <title>Arrays</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + var numOfBeds = 4; + + var roomNumber = reserveRoom(numOfBeds); + printRoom(roomNumber); + + cleanRoom(roomNumber); + printRoom(roomNumber); + } + + function reserveRoom(numberOfBeds) { + var roomNumber = new Array(numberOfBeds); + + for (var idx = 0; idx < roomNumber.length; idx++) { + roomNumber[idx] = "Bed" + idx; + } + + return roomNumber; + } + + function printRoom(roomNumberParameter) { + for (var idx = 0; idx < roomNumberParameter.length; idx++) { + document.writeln(roomNumberParameter[idx] + "<br>"); + } + } + + function cleanRoom(roomNumberParameter) { + for (var idx = 0; idx < roomNumberParameter.length; idx++) { + roomNumberParameter[idx] += " cleaned "; + } + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arraysTwoDim.html b/codeExamples/week1/introductionToJavascript-1/arraysTwoDim.html new file mode 100644 index 0000000000000000000000000000000000000000..76c1bbcf2b5abefae4be18d42d7bcbb7dc0f9d62 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arraysTwoDim.html @@ -0,0 +1,71 @@ +<!doctype html> +<html> + +<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>"); + var firstArray = [ + [10, 20, 30], + [40, 50, 60], + [70, 80, 90] + ]; + printArray(firstArray); + + document.writeln("<h2>Second Data Set</h2>"); + var secondArray = createArray(2, 3); + initializeArray(secondArray, 1); + printArray(secondArray); + + document.writeln("<h2>Third Data Set (Ragged Array)</h2>"); + var thirdArray = [ + [100, 200, 300], + [400], + [700, 800], + [], + [500, 600, 900, 1000] + ]; + printArray(thirdArray); + } + + function createArray(maxRows, maxCols) { + var newArray = new Array(maxRows); + + for (var row = 0; row < maxRows; row++) { + newArray[row] = new Array(maxCols); + } + + return newArray; + } + + function initializeArray(data, initialValue) { + var row, col; + for (row = 0; row < data.length; row++) { + for (col = 0; col < data[row].length; col++) { + data[row][col] = initialValue; + initialValue++; + } + } + } + + function printArray(data) { + var row, col; + for (row = 0; row < data.length; row++) { + for (col = 0; col < data[row].length; col++) { + document.writeln(data[row][col] + " "); + } + document.writeln("<br>"); // why do we need this? + } + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arrowFunc.html b/codeExamples/week1/introductionToJavascript-1/arrowFunc.html new file mode 100644 index 0000000000000000000000000000000000000000..e956d1fa6ff5a3dbfcb41e2b179dda6fd3ea6dd4 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arrowFunc.html @@ -0,0 +1,36 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + let prod2 = x => x * 2; + + let sum = (x, y, z) => x + y + z; + let initialValue = () => 1000; + + let formatted = x => { + x++; + return `Value: ${x}`; + } + + document.writeln(prod2(10) + "<br>"); + document.writeln(sum(10, 2, 4) + "<br>"); + document.writeln(initialValue() + "<br>"); + document.writeln(formatted(5) + "<br>") + + let scores = [10, 1, 44, 200]; + let sortedAttempt1 = scores.sort(); + document.writeln("sortedAttempt1: " + sortedAttempt1 + "<br>"); + let sortedAttempt2 = scores.sort((a, b) => a - b); + document.writeln("sortedAttempt2: " + sortedAttempt2 + "<br>"); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/arrowFunc2.html b/codeExamples/week1/introductionToJavascript-1/arrowFunc2.html new file mode 100644 index 0000000000000000000000000000000000000000..ccdf9762836f28c8006e256d61d1a3c91a99bd84 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/arrowFunc2.html @@ -0,0 +1,86 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + // strict mode is disabled intentionally + // "use strict"; + + // source: + // https://blog.bitsrc.io/a-practical-guide-to-es6-arrow-functions-c16975100cf5 + + const details = { + name: 'Arfat', + getName: function () { + return this.name; + } + } + details.getName(); // 'Arfat' + + // However, in JavaScript, the callback function (and every traditional function) + // gets its own value of this. This value is different from the details object. + // Hence, the getDetails methods has a value of this that is bound to details + // object, and the callback passed to the forEach method has a value of this that + // is not details object. When the callback is searching for the this value, it + // invariably gets its own value first instead of the this value of getFriends + // method. In a sense, the this value of getFriends is shadowed by the callback’s + // own value. + const details2 = { + name: 'Arfat', + friends: ['Bob', 'Alex'], + getFriends: function () { + this.friends.forEach(function (friend) { + console.log(this.name + " is friends with " + friend); + }); + } + } + details2.getFriends(); + + // One solution is to this problem is to use the that = this pattern. Let’s see + // the code + const details3 = { + name: 'Arfat', + friends: ['Bob', 'Alex'], + getFriends: function () { + const that = this; + this.friends.forEach(function (friend) { + console.log(that.name + " is friends with " + friend); + }); + } + } + details3.getFriends(); + + // manual rebinding of this + const details4 = { + name: 'Arfat', + friends: ['Bob', 'Alex'], + getFriends: function () { + this.friends.forEach(function (friend) { + console.log(this.name + " is friends with " + friend); + }, this); + } + } + details4.getFriends(); + + // Arrow functions bind this lexically. In other words, Arrow functions always + // have a value of this keyword taken from the parent scope. That is, they don’t + // have any intrinsic, own this value. + const details5 = { + name: 'Arfat', + friends: ['Bob', 'Alex'], + getFriends: function () { + this.friends.forEach(friend => { + console.log(this.name + " is friends with " + friend); + }); + } + } + details5.getFriends(); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/defaultParameters.html b/codeExamples/week1/introductionToJavascript-1/defaultParameters.html new file mode 100644 index 0000000000000000000000000000000000000000..27b03a732adcf31c1076f787e567ada10a3091c4 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/defaultParameters.html @@ -0,0 +1,47 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + task(); + task("Rose"); + task(25); + task("Kelly", 30, 20000); + taskOld(); + + document.writeln(greet('Hello', 'Chris')); + } + + function task(name = "John", age = 21, salary = special()) { + document.writeln(name + ' ' + age + ' ' + salary + "<br>"); + } + + function taskOld(name, age) { + name = name || "John"; + age = age || 21; + document.writeln("Old approach: " + name + ' ' + age + "<br>"); + } + + function special() { + return 10000; + } + + // Parameters defined beforehand (to the left) are available to later + // default parameters + function greet(name, greeting, message = greeting + ' ' + name) { + return [name, greeting, message]; + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/definingFunctions.html b/codeExamples/week1/introductionToJavascript-1/definingFunctions.html new file mode 100644 index 0000000000000000000000000000000000000000..4ea18ec10d8cd041541a0b9cebfbd1123e3ba033 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/definingFunctions.html @@ -0,0 +1,34 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body onload="main()"> + <script> + main(); + + function main() { + document.writeln(product(3, 4)); + + /* Function expression (anonymous function) */ + var myProduct = function (x, y) { + return x * y; + }; + document.writeln("<br>" + myProduct(100, 200)); + + /* Using Function constructor */ + var thirdProduct = new Function("x", "y", "return x * y"); + document.writeln("<br>" + thirdProduct(2, 3)); + } + + /* Function declaration */ + function product(x, y) { + return x * y; + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/destructuring.html b/codeExamples/week1/introductionToJavascript-1/destructuring.html new file mode 100644 index 0000000000000000000000000000000000000000..ce227c4fb23d3ea9ed2836f923636db30e3b50c6 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/destructuring.html @@ -0,0 +1,46 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Destructuring Example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + /* destructuring arrays */ + let names = ["John", "Mary", "Paul"]; + let [first, second] = names; + document.writeln("First: " + first + ", " + "Second: " + second + "<br>"); + + /* destructuring objects */ + let app = { + name: "mapApp", + developed: 1986 + }; + /* You must use the same property name; try name2 instead of name */ + let { + name, + developed + } = app; /* Notice using { } */ + document.writeln("Name: " + name + ", " + "Developed: " + developed + "<br>"); + + /* swap */ + let a = 100, + b = 200; + [b, a] = [a, b]; + document.writeln(a + ", " + b + "<br>"); + + let [x, y, ...rest] = [10, 20, 30, 40, 50]; + document.writeln(x + ", " + y + ", [" + rest + "]"); + + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/forOf.html b/codeExamples/week1/introductionToJavascript-1/forOf.html new file mode 100644 index 0000000000000000000000000000000000000000..4cd5996b0c90dd956c801fe4bc00bdaef877188a --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/forOf.html @@ -0,0 +1,20 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + let languages = ["C++", "Fortran", "JavaScript"]; + for (let lang of languages) { + document.writeln(lang + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/functionsAsData.html b/codeExamples/week1/introductionToJavascript-1/functionsAsData.html new file mode 100644 index 0000000000000000000000000000000000000000..65966d6060b2ee3e34000984c9916ed8eac5b758 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/functionsAsData.html @@ -0,0 +1,28 @@ +<!doctype html> +<html> + +<head> + <meta charset="UTF-8" /> + <title>Functions as Data</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + var sayHi = hello; + var hi = hello; + hi("John"); + hello("John"); + sayHi("John"); + } + + function hello(name) { + document.writeln(name + "<br />"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/functionsAsData2.html b/codeExamples/week1/introductionToJavascript-1/functionsAsData2.html new file mode 100644 index 0000000000000000000000000000000000000000..46a5d950b33198420e6fd6e475080b1c1fe15909 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/functionsAsData2.html @@ -0,0 +1,50 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Functions as Data</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + var numberOfValues = Number(prompt("Enter number of values to print")); + var wantHTML = window.confirm( + "Press OK for HTML format and Cancel for text"); + var printingFunction; + + if (wantHTML) { + //processValues(numberOfValues, htmlFormat); + printingFunction = htmlFormat; + } else { + //processValues(numberOfValues, textFormat); + printingFunction = textFormat; + } + + processValues(numberOfValues, printingFunction); + } + + function textFormat(data) { + document.writeln(data); + } + + function htmlFormat(data) { + document.writeln("<em><strong>" + data + ", </strong></em>"); + } + + function processValues(maximum, printOption) { + var curr = 1; + while (curr <= maximum) { + printOption(curr); + curr++; + } + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/instanceOf.html b/codeExamples/week1/introductionToJavascript-1/instanceOf.html new file mode 100644 index 0000000000000000000000000000000000000000..610baf9e1c79ee94d950df17fd57db39b59bab74 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/instanceOf.html @@ -0,0 +1,49 @@ +<!doctype html> +<html> + +<head> + <meta charset="UTF-8" /> + <title>charAt Example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function printArray(scores) { + var i; + + for (i = 0; i < scores.length; i++) { + document.writeln("Value " + scores[i] + "<br>"); + } + } + + function main() { + var myInfo = { + name: "John", + id: 10 + }; + + var scores = [10, 30]; + printArray(scores); + + document.writeln("myInfo instance of Object: " + (myInfo instanceof Object) + + "<br>"); + document.writeln("scores instance of Object: " + (scores instanceof Object) + + "<br>"); + document.writeln("scores instance of Array: " + (scores instanceof Array) + "<br>"); + document.writeln("printArray instance of Function: " + ( + printArray instanceof Function) + "<br><br>"); + + document.writeln("typeof myInfo: " + typeof myInfo + "<br>"); + document.writeln("typeof scores: " + typeof scores + "<br>"); + document.writeln("typeof printArray: " + typeof printArray + "<br><br>"); + + document.writeln("Array.isArray(scores): " + Array.isArray(scores) + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/null.html b/codeExamples/week1/introductionToJavascript-1/null.html new file mode 100644 index 0000000000000000000000000000000000000000..0d6535d3bfa2f59b1ca21b51f083d5bf071a85fb --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/null.html @@ -0,0 +1,26 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Null</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + var name = window.prompt( + "Enter your name (select cancel to see result)"); + if (name === null) { + window.confirm("Data input operation cancelled."); + } else { + window.confirm("Welcome: " + name); + } + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/numericValues.html b/codeExamples/week1/introductionToJavascript-1/numericValues.html new file mode 100644 index 0000000000000000000000000000000000000000..afaef2860ee69d82c95554f818cc8e8d9985474d --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/numericValues.html @@ -0,0 +1,47 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Numeric Values</title> +</head> + +<body> + <script> + "use strict"; + + var 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 += "isFinite(null): " + 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>"); + var x = 1 / 7 + 4 / 7 + 2 / 7; + var y = (1 + 4 + 2) / 7; + document.writeln("Value of x: " + x + "<br>"); + document.writeln("Value of y: " + 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/codeExamples/week1/introductionToJavascript-1/randomValues.html b/codeExamples/week1/introductionToJavascript-1/randomValues.html new file mode 100644 index 0000000000000000000000000000000000000000..ef2a573f831e08fd5027dce54d4ad4257d24cb3d --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/randomValues.html @@ -0,0 +1,77 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Random Values</title> +</head> + +<body> + <script> + "use strict"; + main(); + + function main() { + var maximum, menu = "Enter 1 for random values [0, 1)\n"; + menu += "Enter 2 for random values between [0, max)\n"; + menu += "Enter 3 for integer Random values between [0, max]"; + + var choice = Number(prompt(menu)); + var numberOfValues = Number(prompt( + "Enter number of values to generate")); + if (choice === 1) { + simpleRandomCall(numberOfValues); + } else if (choice === 2) { + maximum = Number(prompt("Enter maximum value")); + randomValues(maximum, numberOfValues); + } else if (choice === 3) { + maximum = Number(prompt("Enter maximum value")); + randomIntegerValues(maximum, numberOfValues); + } else { + alert("Invalid choice."); + } + } + + function simpleRandomCall(numberOfValues) { + document.writeln("<h1>Values between 0 and less than 1</h1>"); + document.writeln("<p>"); + + var i = 0; + while (i < numberOfValues) { + document.writeln(Math.random() + "<br>"); + i++; + } + document.writeln("</p>"); + } + + function randomValues(max, numberOfValues) { + document.writeln("<h1>Random values between 0 and less than " + + max + + " </h1>"); + document.writeln("<p>"); + + var i = 0; + while (i < numberOfValues) { + document.writeln((max * Math.random()) + "<br>"); + i++; + } + document.writeln("</p>"); + } + + function randomIntegerValues(max, numberOfCalls) { + document.writeln("<h1>Random integer values between 0 and " + max + + " </h1>"); + document.writeln("<p>"); + + var i = 0; + while (i < numberOfCalls) { + document.writeln(Math.floor((max + 1) * Math.random()) + + "<br>"); + i++; + } + document.writeln("</p>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/restOperator.html b/codeExamples/week1/introductionToJavascript-1/restOperator.html new file mode 100644 index 0000000000000000000000000000000000000000..64d518a05664704ac2697a358d0355128313280b --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/restOperator.html @@ -0,0 +1,30 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Rest Operator Example</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + partyInfo("FirstParty", "John", "Alice", "Peter"); + partyInfo("SecondParty", "Mike", "Sandra"); + } + + function partyInfo(name, director, ...others) { + document.writeln(name + " " + director + "<br>"); + for (let i = 0; i < others.length; i++) { + document.writeln(others[i]); + } + document.writeln("<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/sorting.html b/codeExamples/week1/introductionToJavascript-1/sorting.html new file mode 100644 index 0000000000000000000000000000000000000000..b122e84e6ec9b6e6b24cbd64528d53c6662cbdf3 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/sorting.html @@ -0,0 +1,85 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Sorting</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() { + var names = ["Rose", "Bob", "Tom", "Albert"]; + + document.writeln("Original<br>"); + document.writeln(names.join() + "<br>"); + document.writeln("Sorted<br>"); + names.sort(); + document.writeln(names.join("*") + "<br>"); + + var scores = [30, 2, 4, 5]; + document.writeln("Original<br>"); + document.writeln(scores.join() + "<br>"); + document.writeln("Sorted<br>"); + scores.sort(); // Unicode code point order does generates unexpected result + document.writeln(scores.join(",") + "<br><br>"); + + document.writeln("Using comparison function<br>"); + scores.sort(function (x, y) { + return x - y; + }); + document.writeln(scores.join(",") + "<br><br>"); + + document.writeln("Sorted names<br>"); + names.sort(strCompare); + document.writeln(names.join(",") + "<br>"); + + var students = [{ + name: "John", + id: 3 + }, + { + name: "Peter", + id: 2 + }, + { + name: "Mary", + id: 10 + } + ]; + + document.writeln("Sorting array of objects<br>"); + students.sort(function (x, y) { + return strCompare(x.name, y.name); + }); + for (let i = 0; i < students.length; i++) { + document.writeln(students[i].name + "<br>"); + } + } + + function strCompare(x, y) { + if (x < y) { + return -1; + } else if (x > y) { + return 1; + } else { + return 0; + } + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/spreadOperator.html b/codeExamples/week1/introductionToJavascript-1/spreadOperator.html new file mode 100644 index 0000000000000000000000000000000000000000..77c45cc35e22fa406bf743d2d1778b06b5273697 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/spreadOperator.html @@ -0,0 +1,58 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Spread Operator Example</title> +</head> + +<body> + <script> + "use strict"; + + function process(start, end, delta, message) { + document.writeln(message + "<br>"); + for (let i = start; i <= end; i += delta) { + document.writeln(i + " "); + } + document.writeln("<br>"); + } + + process(1, 10, 2, "First"); + process(...[1, 10, 2, "Second", "Test"]); + /* will not work without spread operator */ + + process(1, ...[10, 2], "Third"); /* will not work without spread operator */ + + let part1 = ["C", "Java"]; + let part2 = ["Python"]; + let combined = ["Pascal", ...part1, ...part2]; + document.writeln(combined.join() + "<br>"); + + var arr = [1, 2, 3]; + var arr2 = [...arr]; // like arr.slice() + arr2.push(4); + document.writeln(arr2 + "<br>"); + + let numArray1 = [1, -21, 3, 4]; + let numArray2 = [9, 3, -8, 10, 7]; + + document.writeln(Math.max(...numArray1, ...numArray2) + "<br>"); + + let string = "CMSC389N"; + let charArr = [...string]; + document.writeln(charArr + "<br>"); + document.writeln(typeof charArr[0] + "<br>"); + + let newArr = Array.from(string).map(x => x.toLowerCase()); + document.writeln(newArr + "<br>"); + + document.writeln("Converting elements of iterable into array<br>"); + let mySet = new Set(); + mySet.add("Mike").add("Rose"); + let myArray = [...mySet]; + document.writeln(myArray.join()); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/sqrTable.html b/codeExamples/week1/introductionToJavascript-1/sqrTable.html new file mode 100644 index 0000000000000000000000000000000000000000..5abc63f6b28141a947f407a0af1e8d107481562c --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/sqrTable.html @@ -0,0 +1,40 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Square Root Table</title> +</head> + +<body> + <script> + "use strict"; + + var 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=\"10\">"); + 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>" + + Math.sqrt(currValue) + "</td></tr>"); + currValue = currValue + 1; + } + + document.writeln("</table>"); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/stringMethods.html b/codeExamples/week1/introductionToJavascript-1/stringMethods.html new file mode 100644 index 0000000000000000000000000000000000000000..392d2e6e0377f94cf75174f9d3a039eb25021036 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/stringMethods.html @@ -0,0 +1,72 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>String Methods</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + var str1 = prompt("Enter string value"); + var str2 = prompt("Enter string value"), + 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(5)→" + str1.repeat(5)); + 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"); + var strArray = str1.split(","), + i; + document.writeln("String components:<br>") + for (i = 0; i < strArray.length; i++) { + document.writeln(strArray[i] + " Length: " + strArray[i].length + "<br>"); + } + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/templateLiteral.html b/codeExamples/week1/introductionToJavascript-1/templateLiteral.html new file mode 100644 index 0000000000000000000000000000000000000000..0bea59d123ba5b69876cc53f4209e9f1afe6a98e --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/templateLiteral.html @@ -0,0 +1,51 @@ +<!doctype html> +<html> + +<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>`; + + letter += body + "<br><br>"; + letter += `Sincerely<br><br><br><br>${signature}`; + + return letter; + } + + function sum(x, y) { + return x + y; + } + + function main() { + let mascot = "turtle"; + let message = `Fear the ${mascot}`; + document.writeln(message); + + document.writeln(getLetter("Mary", "How are you doing?", "Peter")); + let x = 20, + y = 30; + let totalCost = `<br>Total Cost is ${x * y}`; + document.writeln(totalCost); + let sumResult = `<br>Sum is ${sum(x, y)}`; + document.writeln(sumResult); + + const string = `Hello + terps!`; + document.writeln("<pre>"); + document.writeln(string); + document.writeln("</pre>"); + + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/test.js b/codeExamples/week1/introductionToJavascript-1/test.js new file mode 100644 index 0000000000000000000000000000000000000000..7537b8cec290a1ab469319ce3458b59e89071e22 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/test.js @@ -0,0 +1,11 @@ +function test (x){ + return `The number + + + + + + is ${x}`; +} + +console.log(test([1,2,3])); \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/truthyFalsy.html b/codeExamples/week1/introductionToJavascript-1/truthyFalsy.html new file mode 100644 index 0000000000000000000000000000000000000000..3600a355994240536ea7d27b34f01475deab1985 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/truthyFalsy.html @@ -0,0 +1,46 @@ +<!doctype html> +<html> + +<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"; + + isTruthy(false); + isTruthy(0); + isTruthy(""); + isTruthy(null); + isTruthy(undefined); + isTruthy(NaN); + isTruthy("0"); + isTruthy("false"); + isTruthy({}); + isTruthy([]); + isTruthy(Math.PI); + isTruthy("Hello everyone"); + + let date1 = new Date('2019-09-12T12:30:00'); + let date2 = new Date('September 12, 2019 12:30:00') + isTruthy(date1); + isTruthy(date2); + isTruthy(date1 === date2 || date1 == date2); + + // use of Lodash function lib. isEqual performs deep comparison + isTruthy(_.isEqual(date1, date2)); + + var now = new Date(); + isTruthy(now); + + function isTruthy(v) { + (v) ? console.log(v + " is Truthy!"): console.log(v + " is Falsy!"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/validityCheck.html b/codeExamples/week1/introductionToJavascript-1/validityCheck.html new file mode 100644 index 0000000000000000000000000000000000000000..52b61605b939d61dcf21c82494a3e90d2a60eef1 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/validityCheck.html @@ -0,0 +1,43 @@ +<!doctype html> +<html> + +<head> + <meta charset="UTF-8" /> + <title>Validity Check</title> +</head> + +<body> + <script> + "use strict"; + + /* calling main */ + main(); + + function main() { + var value, invalid; + + do { + value = prompt("Enter a number"); + if (value !== null) { + value = value.trim(); + let k = isNaN(value); + invalid = (value === "" || isNaN(value)); + + + + if (invalid) { + alert("You need to enter a number"); + } + } + } while (value !== null && invalid); + + if (value === null) { + alert("No value was provided") + } else { + alert("Value provided: " + value); + } + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-1/varHoisting.html b/codeExamples/week1/introductionToJavascript-1/varHoisting.html new file mode 100644 index 0000000000000000000000000000000000000000..af7fc7dd8b745d44abf9321e3ff819aa0110c527 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-1/varHoisting.html @@ -0,0 +1,29 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Variable Hoisting Example</title> +</head> + +<body> + <script> + "use strict"; + + // initialization won't be hoisted! + document.writeln("<em style='font-size: 3em'>" + x + "</em><br>"); + + x = 389; + document.writeln("<em style='font-size: 3em'>" + x + "</em><br>"); + + // enabling this line will throw an error. Hosting does not work for "let" + // document.writeln("<em style='font-size: 3em'>" + y + "</em><br>"); + + var x = "389n"; + let y = 983; + + document.writeln("<em style='font-size: 3em'>" + y + "</em><br>"); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/addingProperties.html b/codeExamples/week1/introductionToJavascript-2/addingProperties.html new file mode 100644 index 0000000000000000000000000000000000000000..e2899ea3779cce9b9af057abd383afcf3c73f225 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/addingProperties.html @@ -0,0 +1,42 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Adding Properties</title> +</head> + +<body> + <script> + "use strict"; + + main(); + + function main() { + var sale = new Object(); + + /* Reading the items, number of items */ + var wantAnotherItem, item, numberOfItems; + + do { + item = prompt("Enter name of item you want to buy."); + numberOfItems = Number(prompt("Enter number of items you want to buy.")); + sale[item] = numberOfItems; + wantAnotherItem = window.confirm("Do you want to buy another item?"); + } while (wantAnotherItem); + + /* Report about bought items */ + var report = "Items bought\n"; + + /* note: + The for...in statement iterates over all non-Symbol, enumerable properties of + an object */ + for (var propertyName in sale) { + report += propertyName + "-->" + sale[propertyName] + "\n"; + } + alert(report); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/arrayFilter.html b/codeExamples/week1/introductionToJavascript-2/arrayFilter.html new file mode 100644 index 0000000000000000000000000000000000000000..59e809d1b77d3732c4a5c46e47d8ca675f0d71a3 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/arrayFilter.html @@ -0,0 +1,65 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Array filter method Example</title> +</head> + +<body> + <script> + "use strict"; + + var products = [{ + name: "Licensed Metal Fish", + price: 694.00 + }, + { + name: "Tasty Rubber Chicken", + price: 345.00 + }, + { + name: "Handmade Fresh Chicken", + price: 984.00 + }, + { + name: "Ergonomic Frozen Computer", + price: 838.00 + }, + { + name: "Tasty Cotton Tuna", + price: 914.00 + }, + { + name: "Fantastic Steel Mouse", + price: 93.00 + }, + { + name: "Practical Rubber Keyboard", + price: 319.00 + }, + { + name: "Incredible Wooden Hat", + price: 930.00 + }, + { + name: "Fantastic Metal Soap", + price: 351.00 + }, + { + name: "Ergonomic Concrete Mouse", + price: 829.00 + } + ]; + + let filtered = products.filter(p => p.price > 900); + let printProduct = (p) => { + document.writeln(p.name + ", "); + document.writeln(p.price + "<br>"); + }; + + filtered.forEach(printProduct); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/arrayReduce.html b/codeExamples/week1/introductionToJavascript-2/arrayReduce.html new file mode 100644 index 0000000000000000000000000000000000000000..f8ed5e634ec86e98d4adbc4e7cdfa5c1465682ae --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/arrayReduce.html @@ -0,0 +1,65 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Array reduce method Example</title> +</head> + +<body> + <script> + "use strict"; + + var products = [{ + name: "Licensed Metal Fish", + price: 694.00 + }, + { + name: "Tasty Rubber Chicken", + price: 345.00 + }, + { + name: "Handmade Fresh Chicken", + price: 984.00 + }, + { + name: "Ergonomic Frozen Computer", + price: 838.00 + }, + { + name: "Tasty Cotton Tuna", + price: 914.00 + }, + { + name: "Fantastic Steel Mouse", + price: 93.00 + }, + { + name: "Practical Rubber Keyboard", + price: 319.00 + }, + { + name: "Incredible Wooden Hat", + price: 930.00 + }, + { + name: "Fantastic Metal Soap", + price: 351.00 + }, + { + name: "Ergonomic Concrete Mouse", + price: 829.00 + } + ]; + + const reducer1 = (priceSum, p, idx, arr) => priceSum += Number(p.price); + document.writeln(products.reduce(reducer1, 0)); + + const reducer2 = function (priceSum, p, idx, arr) { + return priceSum += Number(p.price); + } + document.writeln(products.reduce(reducer2, 0)); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/iife.html b/codeExamples/week1/introductionToJavascript-2/iife.html new file mode 100644 index 0000000000000000000000000000000000000000..80d6a9e9e457669e46b1a44508ca34015967db6e --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/iife.html @@ -0,0 +1,27 @@ +<!doctype html> +<html> + +<head> + <meta charset="UTF-8" /> + <title>JS IIFE Example</title> +</head> + +<body> + <script> + "use strict"; + + // this variable will be attached to windows global object + var myStar = "Albireo"; + + (function () { + var hiddenStar = "HiddenStar"; + })(); + + // if you uncomment the line below, JS will throw an error: + // Uncaught ReferenceError: hiddenStar is not defined + // hiddenStar; + + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/isPrototypeOf.html b/codeExamples/week1/introductionToJavascript-2/isPrototypeOf.html new file mode 100644 index 0000000000000000000000000000000000000000..e8489cbc870df14a1e092bf3868f987509a48af8 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/isPrototypeOf.html @@ -0,0 +1,41 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Prototypes</title> +</head> + +<body> + <script> + "use strict"; + + function MyNumberType(n) { + this.number = n; + } + + function Student() {} + let s = new Student(); + console.log(Object.prototype.isPrototypeOf(s)); // true + + let anonymous = new function () {} + console.log(Object.prototype.isPrototypeOf(anonymous)); // true + + function StudentAthlete() {} + StudentAthlete.prototype = Object.create(Student.prototype); + let sa = new StudentAthlete(); + + console.log(Object.prototype.isPrototypeOf(sa)); // true + console.log(Student.prototype.isPrototypeOf(sa)); // true + console.log(StudentAthlete.prototype.isPrototypeOf(sa)); // true + console.log(MyNumberType.prototype.isPrototypeOf(sa)); // false + + let arr1 = new Array(2); + console.log(arr1.hasOwnProperty('length')); + + + debugger; + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/map.html b/codeExamples/week1/introductionToJavascript-2/map.html new file mode 100644 index 0000000000000000000000000000000000000000..4f7fa1361811ea211772ec85429f297bd577bdeb --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/map.html @@ -0,0 +1,65 @@ +<!doctype html> +<html> + +<head> + <meta charset="UTF-8" /> + <title>JS Map Example</title> +</head> + +<body> + <script> + "use strict"; + + function printMap(map) { + document.writeln("Map size: " + map.size + "<br>"); + document.writeln("Map Entries<ul>"); + for (let entry of map) { + document.writeln(entry + "<br>"); + } + document.writeln("</ul>"); + } + + let map = new Map(); + map.set("Mike", 88); + map.set("Rose", 90); + map.set("Kelly", 100); + printMap(map); + + document.writeln("<br>Value for Rose: " + map.get("Rose") + "<br>"); + document.writeln("Value for NotInMap: " + map.get("NotInMap") + "<br>"); + document.writeln("map.has(\"Mike\"): " + map.has("Mike") + "<br>"); + + let firstDeletion = map.delete("Rose"); + document.writeln("<br>First deletion (Rose): " + firstDeletion + "<br>"); + let secondDeletion = map.delete("NotInMap"); + document.writeln("Second deletion: " + secondDeletion + "<br>"); + printMap(map); + + document.writeln("<br>Using keys()<br>"); + for (let key of map.keys()) { + document.writeln(key + "<br>"); + } + + document.writeln("<br>Using values()<br>"); + for (let value of map.values()) { + document.writeln(value + "<br>"); + } + + document.writeln("<br>Using map.entries<br>"); + for (let entry of map.entries()) { + document.writeln(entry[0] + ", " + entry[1] + "<br>"); + } + + document.writeln("<br>Using map.entries(2)<br>"); + for (let [key, value] of map.entries()) { + document.writeln(key + ", " + value + "<br>"); + } + + document.writeln("<br>Another Iteration<br>"); + for (let [key, value] of map) { + document.writeln(key + ", " + value + "<br>"); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/objects.html b/codeExamples/week1/introductionToJavascript-2/objects.html new file mode 100644 index 0000000000000000000000000000000000000000..fb60e9359a33e2fe197b78da32adb0c47eed7b36 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/objects.html @@ -0,0 +1,71 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>JS Object Example</title> +</head> + +<body> + <script> + main(); + + function main() { + /* Alternatives for creating an empty object */ + var emptyObject1 = new Object(); + var emptyObject2 = new Object(undefined); + var emptyObject3 = new Object(null); + + /* Boolean Object alternative */ + var booleanObject1 = new Object(true); + var booleanObject2 = new Boolean(true); + + /* Using Object constructor for person object */ + var person1 = new Object(); + /* Adding properties */ + + person1.name = "John"; + person1.age = 45; + person1.school = umcpSchool; + + printPerson(person1); + + /* Using object initializer/literal notation */ + var person2 = { + name: "Mary", + age: 30, + school: umcpSchool, + bestFriend: person1 + }; + + printPerson(person2); + + var exam = { + semester: "fall", + "difficulty-level": 10, + 3: "midterm3", + "": "empty string" + }; + + // NOT VALID alert("First form: " + exam.difficulty-level); + document.writeln("difficulty-level: " + exam["difficulty-level"] + "<br>"); + document.writeln("exam[3]: " + exam[3] + "<br>"); + document.writeln("'': " +exam[''] + "<br>"); + } + + 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> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/set.html b/codeExamples/week1/introductionToJavascript-2/set.html new file mode 100644 index 0000000000000000000000000000000000000000..1f1c8a89f8cb07b005a990d2e43da48740ff0a7e --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/set.html @@ -0,0 +1,60 @@ +<!doctype html> +<html> + +<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 + }; + mySet.add(150); + mySet.add(student1).add(student2); /* add is chainable */ + + document.writeln("150 part of the set? " + mySet.has(150) + "<br>"); + document.writeln("Set size: " + mySet.size + "<br>"); + document.writeln("Set Entries<br>"); + for (let entry of mySet) { + document.writeln(entry + "<br>"); + } + + document.writeln("<br>After deleting an entry<br>"); + mySet.delete(student1); + for (let entry of mySet) { + document.writeln(entry + "<br>"); + } + + document.writeln("<br>After clearing the set<br>"); + mySet.clear(); + for (let entry of mySet) { + document.writeln(entry + "<br>"); + } + + document.writeln("<br>Set based on array<br>"); + let arr = ["C", "JavaScript", "Pascal"]; + document.writeln(arr + "<br>"); + + let setFromArray = new Set(arr); + + document.writeln("<ul>"); + let iter = setFromArray.values(); + for (let e of iter) { + document.writeln("<li>" + e + "</li>") + } + document.writeln("</ul>"); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/symbol.html b/codeExamples/week1/introductionToJavascript-2/symbol.html new file mode 100644 index 0000000000000000000000000000000000000000..50e345bb795393f83f3f7ee09778e44ece4623ce --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/symbol.html @@ -0,0 +1,65 @@ +<!doctype html> +<html> + +<head> + <meta charset="UTF-8" /> + <title>JS Example</title> +</head> + +<body> + <script> + "use strict"; + + let sym = Symbol("firstSymbol"); + + document.writeln(String(sym) + + "<br>"); /* implicit convertion does not work */ + document.writeln(sym.toString() + + "<br>"); /* implicit convertion does not work */ + + let sym2 = Symbol("firstSymbol"); + if (sym === sym2) { + document.writeln("Symbols the same<br>"); + } else { + document.writeln("Symbols are different<br>"); + } + document.writeln("typeof sym: " + typeof sym + "<br>"); + + /* symbol as property key */ + const KEY_TO_USE = Symbol('a key to use'); + const computedPropKey = "prop" + 0; + let myObj = { + name: "John", + [computedPropKey]: 3000, + [KEY_TO_USE]: 789, // a computed prop key + ['home' + 'address']: "somewhere in maryland", // a computed prop key + [300 + 80 + 9]: "a computed property key!" // a computed prop key + }; + document.writeln("myObj[KEY_TO_USE]: " + myObj[KEY_TO_USE] + "<br>"); + document.writeln("myObj[computedPropKey]: " + myObj[computedPropKey] + "<br>"); + document.writeln(Object.getOwnPropertyNames(myObj) + "<br>"); + document.writeln(String(Object.getOwnPropertySymbols(myObj)[0]) + "<br>"); + + // note that [KEY_TO_USE] is ignored in the for-in loop + document.writeln("<br>for..in<br>"); + let text = ""; + for (let prop in myObj) { + text += "'" + myObj[prop] + "' "; + } + document.writeln("<br>" + text + "<br>"); + + const MESSAGE = Symbol(); + let testudo = { + [MESSAGE]: function () { + return 'Fear the turtle'; + } + }; + document.writeln("<br>Message is " + testudo[MESSAGE]() + "<br>"); + + const COLOR_RED = Symbol("Red"); + const COLOR_BLUE = Symbol("Blue"); + document.writeln("Boolean(COLOR_RED): " + Boolean(COLOR_RED) + "<br>"); + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/symbolUse.html b/codeExamples/week1/introductionToJavascript-2/symbolUse.html new file mode 100644 index 0000000000000000000000000000000000000000..1e89e8a8ab6f04a26edca014a646e50ec6830098 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/symbolUse.html @@ -0,0 +1,82 @@ +<!doctype html> +<html> + +<head> + <meta charset="UTF-8" /> + <title>JS Symbol Usage Example</title> +</head> + +<body> + + <script> + // "use strict"; + + const iterableObject = { + + item1: 'value1', + item2: 'value2', + + [Symbol.iterator]() { + this.current = 0; + return this; + }, + + next() { + if (this.current === 0) { + this.current++; + return { + done: false, + value: this.item1 + }; + } else if (this.current === 1) { + this.current++; + return { + done: false, + value: this.item2 + }; + } else { + return { + done: true + }; + } + } + } + + for (const p of iterableObject) { + console.log(p); + } + + const iterableObject2 = { + data: ['hello', 'world', 'always'], + + [Symbol.iterator]: function () { + // returns an iterator object + return { + current: 0, + data: this.data, + + next() { + if (this.current < this.data.length) { + // console.log(this.current + " " + this.last); + // console.log(this.data); + return { + done: false, + value: this.data[this.current++] + }; + } else { + return { + done: true + }; + } + } + }; + } + }; + + for (const p of iterableObject2) { + console.log(p); + } + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/introductionToJavascript-2/valueOf.html b/codeExamples/week1/introductionToJavascript-2/valueOf.html new file mode 100644 index 0000000000000000000000000000000000000000..6aae8617916831ad2f95b322ade2b821ddd810f4 --- /dev/null +++ b/codeExamples/week1/introductionToJavascript-2/valueOf.html @@ -0,0 +1,53 @@ +<!doctype html> +<html> + +<head> + <meta charset="utf-8" /> + <title>Prototypes</title> +</head> + +<body> + <script> + "use strict"; + + function MyNumberType(n) { + this.number = n; + } + + // executed when primitive type is expected + MyNumberType.prototype.valueOf = function () { + return this.number; + }; + + // executed when string is expected + MyNumberType.prototype.toString = function () { + return "Number is " + this.number; + }; + + // ES6 - The Symbol.toPrimitive is a symbol that specifies a function + // valued property that is called to convert an object to a corresponding + // primitive value. + MyNumberType.prototype[Symbol.toPrimitive] = function (hint) { + // hint is one of "string", "number", "default" + console.log(hint); + + if (hint === "string") { + return this.toString(); + } else if (hint === "number") { + return this.valueOf(); + } else { // default + return this.valueOf(); + } + } + + const object1 = new MyNumberType(4); + + console.log(object1.number); // 4 + console.log(object1 + 3); // default + console.log(object1 + " string concatenated"); // default + console.log(`${object1}`); // string + alert(object1); // string + </script> +</body> + +</html> \ No newline at end of file diff --git a/codeExamples/week1/nodeBasics/SampleWebpage.html b/codeExamples/week1/nodeBasics/SampleWebpage.html new file mode 100644 index 0000000000000000000000000000000000000000..b58e6efcf86fdf13ab81166676fbdbe036007e8f --- /dev/null +++ b/codeExamples/week1/nodeBasics/SampleWebpage.html @@ -0,0 +1,20 @@ +<!doctype html> +<html> + <head> + <meta charset="utf-8" /> + <!-- For responsive page --> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <meta name="description" content="Basic HTML5 Document" /> + <meta name="keywords" content="HTML5, Responsive, CMSC389N"/> + <link href="favicon.ico" rel="icon" type="image/x-icon" /> + <title>HTML TEMPLATE</title> + </head> + + <body> + <ol type = "I"> + <li>Shakira</li> + <li>JLo</li> + + </ol> + </body> +</html> \ No newline at end of file diff --git a/codeExamples/week1/nodeBasics/add.js b/codeExamples/week1/nodeBasics/add.js new file mode 100644 index 0000000000000000000000000000000000000000..e018112bb728c791c7fd6b5b3cf160202cdffe2b --- /dev/null +++ b/codeExamples/week1/nodeBasics/add.js @@ -0,0 +1,27 @@ +class Person{ + constructor(name, age){ + this.name = name; + this.age = age; + } + + toString(){ + return "Name is: " + this.name + " age is " +this.age; + } + +} + +class Student{ + constructor(name, gpa){ + this.name = name; + this.gpa = gpa; + } + + toString(){ + return "Name is: " + this.name + " gpa is " +this.gpa; + } + +} + +module.exports.Person = Person; +module.exports.Stu = Student; + diff --git a/codeExamples/week1/nodeBasics/eventEmitterExample.js b/codeExamples/week1/nodeBasics/eventEmitterExample.js new file mode 100644 index 0000000000000000000000000000000000000000..c2a1e9abbe86fe434e8069fa284926719d4a1f02 --- /dev/null +++ b/codeExamples/week1/nodeBasics/eventEmitterExample.js @@ -0,0 +1,19 @@ +var emitter = require('events').EventEmitter; + +var em = new emitter(); + +//Subscribe FirstEvent +em.addListener('FirstEvent', function (data) { + console.log('First subscriber: ' + data); +}); + +//Subscribe SecondEvent +em.on('SecondEvent', function (data) { + console.log('First subscriber: ' + data); +}); + +// Raising FirstEvent +em.emit('FirstEvent', 'This is my first Node.js event emitter example.'); + +// Raising SecondEvent +em.emit('SecondEvent', 'This is my second Node.js event emitter example.'); \ No newline at end of file diff --git a/codeExamples/week1/nodeBasics/eventsExample.js b/codeExamples/week1/nodeBasics/eventsExample.js new file mode 100644 index 0000000000000000000000000000000000000000..0ab901d82cc458518697f131a81cf191a9544325 --- /dev/null +++ b/codeExamples/week1/nodeBasics/eventsExample.js @@ -0,0 +1,16 @@ +//const EventEmitter = require('events'); +const RaiseEvent = require('./raise'); + +const myEmitter = new RaiseEvent(); + +//on +myEmitter.on('Greeting', function(){ + console.log("I was just greeted!"); +}) + +myEmitter.on('High Five', function(args){ + console.log(args); +}) + + +myEmitter.raise(); diff --git a/codeExamples/week1/nodeBasics/fsExample.js b/codeExamples/week1/nodeBasics/fsExample.js new file mode 100644 index 0000000000000000000000000000000000000000..3e699bd5f6a0879dcdb034e1a41eba6df07a1786 --- /dev/null +++ b/codeExamples/week1/nodeBasics/fsExample.js @@ -0,0 +1,20 @@ +const fs = require('fs'); + + +fs.readdir('/Users/tesla/teaching/summer2020/cmsc389N/cmsc389nsummer2020-student/lectureCodeExamples/week5/node/', function (err, files){ + if(err){ + console.log(err); + }else{ + console.log(files); + } + + +}); + + +fs.appendFile('/Users/tesla/teaching/summer2020/cmsc389N/cmsc389nsummer2020-student/lectureCodeExamples/week5/node/pathExample.js', 'console.log(\'HI!\')', function(err){ + if(err){ + console.log('File didn\'t work yo'); + } + +}); \ No newline at end of file diff --git a/codeExamples/week1/nodeBasics/httpExample.js b/codeExamples/week1/nodeBasics/httpExample.js new file mode 100644 index 0000000000000000000000000000000000000000..72926ce12433e522b0134350fae688a39f399348 --- /dev/null +++ b/codeExamples/week1/nodeBasics/httpExample.js @@ -0,0 +1,15 @@ +const http = require('http'); + +const server = http.createServer(function(request, response){ + if(request.url === '/greeting'){ + response.write('Hi'); + + response.end(); + } +} );//1 + +server.on('connection', function(socket){ + console.log("Connected!"); +}); + +server.listen(5500); \ No newline at end of file diff --git a/codeExamples/week1/nodeBasics/httpFile.js b/codeExamples/week1/nodeBasics/httpFile.js new file mode 100644 index 0000000000000000000000000000000000000000..60598b4f174c386078b9701e7600ea6de041ff5d --- /dev/null +++ b/codeExamples/week1/nodeBasics/httpFile.js @@ -0,0 +1,20 @@ +const http = require('http'); +const fs = require('fs'); + +const server = http.createServer(function (req, res) { + if (req.url === '/sample') { + fs.readFile('./SampleWebpage.html', function (err, data) { + if (err) { + console.log(err); + } else { + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.write(data); + res.end(); + } + + + }) + } +}); + +server.listen(3000); \ No newline at end of file diff --git a/codeExamples/week1/nodeBasics/index.js b/codeExamples/week1/nodeBasics/index.js new file mode 100644 index 0000000000000000000000000000000000000000..35426ddee767760f1410fa612ed58e34a4c53235 --- /dev/null +++ b/codeExamples/week1/nodeBasics/index.js @@ -0,0 +1,8 @@ +const modules = require('./add'); + +let p1 = new modules.Person("Jessica", 35); +let s1 = new modules.Stu("Amy", 3.5); + +console.log(p1.toString()); + +console.log(s1.toString()); \ No newline at end of file diff --git a/codeExamples/week1/nodeBasics/osExample.js b/codeExamples/week1/nodeBasics/osExample.js new file mode 100644 index 0000000000000000000000000000000000000000..82544204d939df34eeac597d437689dd78e5dc08 --- /dev/null +++ b/codeExamples/week1/nodeBasics/osExample.js @@ -0,0 +1,7 @@ +const os = require('os'); + +console.log(os.totalmem()); +console.log(os.freemem()); + +console.log(os.type()); +console.log(os.uptime()); diff --git a/codeExamples/week1/nodeBasics/pathExample.js b/codeExamples/week1/nodeBasics/pathExample.js new file mode 100644 index 0000000000000000000000000000000000000000..883d065e24ecb0ee2f47674bc266e39c0bc05b2f --- /dev/null +++ b/codeExamples/week1/nodeBasics/pathExample.js @@ -0,0 +1,4 @@ +const path = require('path'); + +let p = path.parse('/Users/tesla/teaching/summer2020/cmsc389N/cmsc389nsummer2020-student/lectureCodeExamples/week5/node/pathExample.js'); +console.log(p); \ No newline at end of file diff --git a/codeExamples/week1/nodeBasics/pthExample.js b/codeExamples/week1/nodeBasics/pthExample.js new file mode 100644 index 0000000000000000000000000000000000000000..e188bcef6cb7c56ac085eb4d908d0a87d992079f --- /dev/null +++ b/codeExamples/week1/nodeBasics/pthExample.js @@ -0,0 +1 @@ +console.log('HI!') \ No newline at end of file diff --git a/codeExamples/week1/nodeBasics/raise.js b/codeExamples/week1/nodeBasics/raise.js new file mode 100644 index 0000000000000000000000000000000000000000..f58a6e3c07a1a3dfeb8b41ecc867640cc4b5c3aa --- /dev/null +++ b/codeExamples/week1/nodeBasics/raise.js @@ -0,0 +1,15 @@ +const EventEmitter = require('events'); + +class RaiseEvent extends EventEmitter{ + + + raise() { + //emit events + this.emit('Greeting'); + + this.emit('High Five', "Down Low", "too slow"); + } +} + + +module.exports = RaiseEvent; diff --git a/lectures/week1/JS Day 1.pdf b/lectures/week1/JS Day 1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..f4cb0151cb86d53c42e220246999b46e2bab41c5 Binary files /dev/null and b/lectures/week1/JS Day 1.pdf differ diff --git a/lectures/week1/JS Intro Part 3.pdf b/lectures/week1/JS Intro Part 3.pdf new file mode 100644 index 0000000000000000000000000000000000000000..c49e3222f9f2e4f0a120cddb51cca892e3c5dc86 Binary files /dev/null and b/lectures/week1/JS Intro Part 3.pdf differ diff --git a/lectures/week1/Javascript Object APIS.pdf b/lectures/week1/Javascript Object APIS.pdf new file mode 100644 index 0000000000000000000000000000000000000000..54559222100afeff86179235b075d6208c07adda Binary files /dev/null and b/lectures/week1/Javascript Object APIS.pdf differ