Skip to content
Snippets Groups Projects
Commit e9105b7b authored by Andrej Rasevic's avatar Andrej Rasevic
Browse files

adding week1 material

parent cd7820e2
No related branches found
No related tags found
No related merge requests found
Showing
with 1058 additions and 0 deletions
<!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
<!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
<!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
<!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] + "&nbsp;&nbsp;");
}
document.writeln("<br>"); // why do we need this?
}
}
</script>
</body>
</html>
\ No newline at end of file
<!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
<!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
<!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
<!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
<!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
<!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
<!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
<!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
<!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
<!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
<!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
<!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
<!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
<!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
<!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
<!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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment