Javascript Demo
Testing javascript in jupyter notebook.
console.log("hello world");
var msg = "hello";
console.log(msg);
function add(x1, x2) {
var sum = x1 + x2;
console.log(sum);
}
add(5, 6);
add(19, 37);
function logItType(output) {
console.log(typeof output, ";", output);
}
logItType("hello");
logItType(2020);
logItType([1, 2, 3]);
var testHTML = "Hello World";
$$.html(testHTML);
// define a function to hold data for a Person
function Person(name, ghID) {
this.name = name;
this.ghID = ghID;
this.group = "";
}
// define a setter for role in Person data
Person.prototype.setGroup = function(group) {
this.group = group;
}
// define a JSON conversion "method" associated with Person
Person.prototype.toJSON = function() {
const obj = {name: this.name, ghID: this.ghID, group: this.group};
const json = JSON.stringify(obj); // json/string is useful when passing data on internet
return json;
}
var me = new Person("Sahil", "AD1616");
me.setGroup("Bread");
logItType(me);
logItType(me.toJSON());
var group1 = [
new Person("Sahil", "AD1616"),
new Person("Nathan", "NathanShih04"),
new Person("Rohit", "rohitd3"),
new Person("Kurtis", "kkwan0")
];
function Group(members, groupName) {
this.group = [];
this.members = members;
this.members.forEach(member => {member.setGroup(groupName); this.group.push(member); });
this.json = [];
this.group.forEach(person => this.json.push(person.toJSON()));
}
bread = new Group(group1, "Bread");
logItType(bread.group);
// define an HTML conversion "method" associated with Classroom
Group.prototype._toHtml = function() {
// HTML Style is build using inline structure
var style = (
"display:inline-block;" +
"border: 2px solid grey;" +
"box-shadow: 0.8em 0.4em 0.4em grey;"
);
// HTML Body of Table is build as a series of concatenations (+=)
var body = "";
// Heading for Array Columns
body += "<tr>";
body += "<th><mark>" + "Name" + "</mark></th>";
body += "<th><mark>" + "GitHub ID" + "</mark></th>";
body += "<th><mark>" + "Group" + "</mark></th>";
body += "</tr>";
// Data of Array, iterate through each row of compsci.classroom
for (var row in bread.group) {
// tr for each row, a new line
body += "<tr>";
// td for each column of data
body += "<td>" + bread.group[row].name + "</td>";
body += "<td>" + bread.group[row].ghID + "</td>";
body += "<td>" + bread.group[row].group + "</td>";
// tr to end line
body += "<tr>";
}
// Build and HTML fragment of div, table, table body
return (
"<div style='" + style + "'>" +
"<table>" +
body +
"</table>" +
"</div>"
);
};
// IJavaScript HTML processor receive parameter of defined HTML fragment
$$.html(bread._toHtml());