CS 151 - Day 15

Cover page image

Cay S. Horstmann

Day 15 Clicker Question 1

What is the type of this JavaScript object?

const point = { x: 3, y: 4 }
  1. point
  2. object
  3. Point
  4. None of the above—JavaScript has no objects

Day 15 Clicker Question 2

Which of these prints all elements of an array?

  1. for (let i = 0; i < arr.length; i++)
      console.log(arr[i])
  2. for (const element of arr)
      console.log(element)
  3. for (const key in arr)
      console.log(arr[key])
    
  4. All of the above

Day 15 Clicker Question 3

Consider the function

function larger(x, y) {
  if (x > y) return x
}
What is the result of the function call
const result = larger('3', '20')

  1. 20
  2. '20'
  3. '3'
  4. undefined

Lab

lab

JavaScript Tool Installation

  1. Install NodeJS and npm. In Ubuntu:
    sudo apt install nodejs npm
  2. Install the Standard code checker and the Jest unit test framework:
    sudo npm install standard --global
    sudo npm install jest --global

Graphs

  1. Discuss with your partner how you can store a diagram such as the simple graph from ch08/graphed2 or a UML diagram like in Violet, using JavaScript objects and arrays.
  2. Look up in ch08/graphed2/Graph.java how the graph editor framework stores graphs.
  3. Let's imitate that in JavaScript. Make an object describing a white circle node at some location, and one describing a black circle node somewhere else, and a line edge joining the two. What are your objects? Put them in a file lab15/graph.js.
  4. Add console.log statements to lab15/graph.js that logs your objects. Run the file:
    cd ~/cs151/lab15
    node lab15.js
  5. Before doing anything else, add the line
    'use strict'
    to the top of your JavaScript file, before the variable declarations. We always want to run strict mode.
  6. Now make a JavaScript object that describes the graph with these nodes and edges. Do exactly what is done in Java.
  7. Still in lab15/graph.js, write a function findNode that works like Graph.findNode. Pass the graph object and the point (in some way, either as an object or as two values) to the function. Return the node. For now, just check if the location of the node and the point are exactly the same--you don't know yet how to invoke contains on a node.
  8. Add a console.log statement to lab15/graph.js that calls your function and prints the result.
  9. Write a test case, following the Jest Getting Started guide. Run your test case.
  10. Run your code through the Standard.js checker. Simply run
    standard
    in the lab15 directory.
  11. Still in lab15/graph.js, write a function neighbors that, given a graph and a node, yields an array of neighboring nodes. (You need to know how to add something to the end of a JS array. arr.push(obj) does that—it's like ArrayList.add in Java.)
  12. Extra time? Port other methods from ch08/graphed2/Graph.java can you port to JavaScript. These will soon come in handy.