5 Scripting

Scripting

Objective

  1. Arrays, objects, and functions.
  2. Array methods: Array.method().
  3. Anonymous functions: function () {}.
  4. Arrow notation: () => {}.
  5. Spread/rest operator: ....
  6. Plain old JavaScript objects (POJO): { key: value }.

1 Basics

Install the latest LTS version of Node.js (opens in a new tab).

  1. Use a while loop to display the odd numbers between 1 and 100, inclusive.
  2. Rewrite the previous task using a for loop.
  3. Declare an array with the following values: const cars = ["Toyota", "Honda", "BMW"].
  4. Add "Volvo" to the end of the array and "Mercedes" to the beginning of the array.
  5. Create a show(•) function that takes an array as argument and prints the array elements using a for-of loop.
  6. Call the show(•) function to show the cars array.
  7. Sort the array, in lexicographical order, and show it again.
script.js
// print odd numbers between 1 and 100
while (•) {
  •;
}
 
// print odd numbers between 1 and 100
for (•; •; •) {
  •;
}
 
const cars = ["Toyota", "Honda", "BMW"];
 
// add "Volvo" to the end of cars
 
// add "Mercedes" to the beginning of cars
 
function show(array) {
  for (• of •) {
    •;
  }
}
 
// show cars
 
// sort cars
 
// show cars

2 Arrays

Declare and use the following array of arrays:

script.js
const array = [
  [2, 3],
  [34, 89],
  [55, 101, 34],
  [34, 89, 34, 99],
];

Implement and test the following functions:

  • flatten(•) returns a single-dimensional flat version of the array.
  • sortd(•) sorts the array in descending order, from largest to smallest.
  • max(•) computes the largest value in the array.
  • square(•) returns the array with each element squared.
  • total(•) computes the total value of the array.
  • average(•) computes the average value of the array.
  • sumg40(•) computes the sum of array elements that are greater than 40.
  • distinct(•) returns the array without duplicate elements.

You should try and write these functions as single statements.

Complete the 1 Higher-Order Functions tutorial to learn more about higher-order functions.

3 Objects

  1. Install the prompt-sync package by executing the following commands using a command-line interpreter (shell), which is accessible through the integrated terminal in Visual Studio Code:

    npm install --save prompt-sync
  2. Change your module format type to module (opens in a new tab) in package.json:

    package.json
    {
      "type": "module",
      "dependencies": {
        "prompt-sync": "^4.2.0"
      }
    }
  3. Import and use the prompt-sync package in your script:

    script.js
    import promptSync from "prompt-sync";
    const prompt = promptSync();
    const number = prompt("How many? ");
    console.log(number);
  4. Implement a readStudents() function that prompts the user to input the name and gender of 5 students. Within the function, assign a random age between 17 and 35, and a random grade between 0 and 100 for each student.

    Store the information for each student in an array of objects, where each object represents a student and contains their name, gender, age, and grade. Return the array of student objects.

  5. Create an empty students array and call the readStudents() to populate it. Here is an example of how the array should look like after the call:

    [
      { name: "John", gender: "Male", grade: 85, age: 23 },
      { name: "Jane", gender: "Female", grade: 77, age: 31 },
      { name: "Dohn", gender: "Male", grade: 92, age: 29 },
      { name: "Fane", gender: "Female", grade: 63, age: 20 },
      { name: "Xohn", gender: "Male", grade: 54, age: 22 },
    ];
  6. Write and test functions, using array methods instead of traditional loops, that compute the following:

    1. Find the youngest student.
    2. Find the oldest student.
    3. Compute the average student age.
    4. Compute the median student age.
    5. Compute the average student grade: μ=1ni=1nxi\mu = \frac{1}{n}\sum_{i=1}^{n}x_i.
    1. Compute the variance of the student grades: σ2=1ni=1n(xiμ)2\sigma^2 = \frac{1}{n}\sum_{i=1}^{n}(x_i - \mu)^2.
    2. Get the students by gender, to return either male or female students.
    3. Compute the average grade for male students.
    4. Display the student information sorted in alphabetical order by name.
    5. Display the student information sorted in descending order by grade.
    6. Find the student(s) with the highest grade.
    7. Find the student(s) with the highest grade among the female students.
    8. Determine if there are any students with failing grades, that is, below 60.
    9. Display the student information with an additional property that indicates whether the student has a passing grade, that is, 60 or higher.

4 Shopping Cart

Create a simple shopping app that allows users to add an item to the cart, change item quantities, delete an item, and display the invoice. Use an array of objects to store the catalog of products:

main.js
const products = [
  { id: 1, name: "Apple iPhone Pro Max", price: 4500 },
  { id: 2, name: "Apple iPad Pro 12.9-inch", price: 5600 },
  { id: 3, name: "Samsung Galaxy Ultra", price: 3900 },
  { id: 4, name: "Microsoft Surface Book", price: 6700 },
  { id: 5, name: "Sony PlayStation Pro", price: 3500 },
  { id: 6, name: "Dell XPS 13", price: 4500 },
  { id: 7, name: "LG 75-inch OLED TV", price: 9800 },
  { id: 8, name: "Bose QuietComfort", price: 1800 },
  { id: 9, name: "Sony Wireless Headphones", price: 1600 },
];

Here is how the main menu should look like:

(1) Add item
(2) Change quantity
(3) Delete item
(4) Display invoice
  1. Add item: Display the list of available products and allows the user to enter the desired products and quantities to add the shopping cart; the user can add multiple products to the cart. In case an item already exists in the cart, you should increment only the quantity to avoid adding duplicate items to the cart.

  2. Change quantity: The user will be presented with a list of items currently in their cart along with their quantities. The user can then select an item to update and provide a new quantity for that item. The corresponding item in the cart will be updated with the new quantity. If the selected item does not exist in the cart, display a message indicating that the item could not be found in the cart.

  3. Delete item: Display the list of items in the cart and allow the user to input the product id to be removed from the cart. If the item exists in the cart, remove it, and display a message to confirm its removal. If the item does not exist, display a message indicating that the item could not be found in the cart.

  4. Display invoice: Display the cart items along with their quantities and prices. Also display the total price for all items in the cart. Highlight the most expensive and the least expensive items in the cart with an asterisk and a double asterisk, respectively.

Implement this exercise in a modular fashion, while using array methods, anonymous functions, object literals, and other language features.

Resources