Devember - Learning JavaScript

Day 9

Higher-order functions today!

Creating a shorter-named variable for a long-named function:

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
}

const is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;
is2p2();
console.log(is2p2.name);

I am starting to lose hope. They have had me write this code which I think I did right, but tbh I don’t know how to check that I did. I’m not even 100% sure what this code even does:

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
};

const addTwo = num => num + 2;

const timeFuncRuntime = funcParameter => {
  let t1 = Date.now();
  funcParameter();
  let t2 = Date.now();
  return t2 - t1;
};

const time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes);

const checkConsistentOutput = (func, val) => {
    let firstTry = func(val);
    let secondTry = func(val);
    if (firstTry === secondTry) {
        return firstTry
    } else {
        return "This function returned inconsistent results"
    }
};

checkConsistentOutput(addTwo, 4);

I am getting really frustrated with the design of this course now. :frowning:

2 Likes

What don’t you know? The layout of a for loop and what the parts mean?
The layout of the functions?
It is probably a good time to starting looking at some documentation for Javascript to see if you can get your head around it. The terminology might be weird, because programmers like bringing back obscure words from history and give them newish meanings.

When I run the code the console displays nothing. I know I haven’t put any console.log() in there but what is the return keyword doing? I know it stops the code block from continuing, does it simply make the function output the value after the return keyword?

Ah yes. In the case of the for loop, it is checking that 2 + 2 == 4, a million times. If it doesn’t, it prints a message. If it ever prints a message, your computer is broken!

The rest is tricky…
time2p2 seems to be timing how long it takes to execute the for loop? You could print this value and see. It is tricky because it passes a function name to the timeFuncRuntime function, which gets the time, executes it, and gets another time, subtracts.

The last one executes a function (func in this case, or addTwo as it is passed in the last time), and checks if the output is the same both times. If not, your computer is broken again.

So yeah, nothing should print under normal circumstances. Which probably doesn’t help the understanding of what is going on. So, add more print instructions! Print out the value of time2p2 for example.

I just spent 5 minutes trying to change my arguments for

console.log(checkConsistentOutput(addTwo, 4));

to get it to log “This function returned inconsistent results” before realising that it’s not going to do that because the function works! :smile:

You could try this:
console.log(checkConsistentOutput(addTwo, 5));

1 Like

That logs 7.

Day 10

Today I will be learning about iterators. .forEach() is a nice iterator. I like it.

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

fruits.forEach(fruit => console.log(`I want to eat a ${fruit}.`));

Finding it hard to keep up with function declaration, expression and arrow notation. Find myself going over past examples to refresh my memory a lot.

.map()

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

const secretMessage = animals.map(letter => {
  return letter[0];
});

console.log(secretMessage.join(''));

const bigNumbers = [100, 200, 300, 400, 500];

const smallNumbers = bigNumbers.map(number => {
  return number / 100;
});

I feel like I’m getting the hang of arrow notation again. Here’s some .filter() very similar to .map.

const randomNumbers = [375, 200, 3.14, 7, 13, 852];

const smallNumbers = randomNumbers.filter(number => {
  return number < 250;
});

const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];


const longFavoriteWords = favoriteWords.filter(word => {
  return word.length > 7;
});

Breezed through the .findIndex() work:

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex(animal => {
  return animal === "elephant";
});

const startsWithS = animals.findIndex(animal => {
  return animal[0] === "s";
});

Enjoying the .reduce() exercise too! It’s funny how the moment something clicks my enjoyment shoots up. I love the feeling of learning!

const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue) => {
  console.log('The value of accumulator: ', accumulator);
  console.log('The value of currentValue: ', currentValue);
  return accumulator + currentValue;
}, 10);

console.log(newSum);

Fixing and filling in incomplete code to turn this:

const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];

// Something is missing in the method call below

console.log(words.some(() => {
  return word.length < 6;
}));

// Use filter to create a new array



// Make sure to uncomment the code below and fix the incorrect code before running it

// console.log(interestingWords.every((word) => { } ));

Into this:

const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];

console.log(words.some((word) => {
  return word.length < 6;
}));

const interestingWords = words.filter(word => {
  return word.length > 5;
});

console.log(interestingWords.every((word) => {
return word.length > 5;
} ));

Final exercise of the day, choosing which method each bit of code should use:

const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];

const nums = [1, 50, 75, 200, 350, 525, 1000];

//  Choose a method that will return undefined
cities.forEach(city => console.log('Have you visited ' + city + '?'));

// Choose a method that will return a new array
const longCities = cities.filter(city => city.length > 7);

// Choose a method that will return a single value
const word = cities.reduce((acc, currVal) => {
  return acc + currVal[0]
}, "C");

console.log(word)

// Choose a method that will return a new array
const smallerNums = nums.map(num => num - 5);

// Choose a method that will return a boolean value
nums.some(num => num < 0);

I’m back to enjoying myself again and feeling the frustration melt away. I can tell this journey is going to be a loop of this experience and I will go through many iterations of it! :stuck_out_tongue:

2 Likes

Day 11

An object literal:

let fasterShip = {
  color: "silver",
  "Fuel Type": "Turbo Fuel"
};

Similar to template literal in that it uses {}. Is that what makes something a literal?

Accessing object properties via dot notation:

let spaceship = {
  homePlanet: 'Earth',
  color: 'silver',
  'Fuel Type': 'Turbo Fuel',
  numCrew: 5,
  flightPath: ['Venus', 'Mars', 'Saturn']
};

let crewCount = spaceship.numCrew;
let planetArray = spaceship.flightPath;

Accessing object properties via bracket notation:

let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
  'Active Mission' : true,
  homePlanet : 'Earth', 
  numCrew: 5
 };

let propName =  'Active Mission';

let isActive = spaceship["Active Mission"];
console.log(spaceship["Active Mission"]);

Mutating objects by reassigning and deleting properties:

let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
  homePlanet : 'Earth',
  color: 'silver',
  'Secret Mission' : 'Discover life outside of Earth.'
};

spaceship.color = "glorious gold";
spaceship.numEngines = 6;
delete spaceship["Secret Mission"];

Creating methods:

let retreatMessage = 'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.';

let alienShip = {
  retreat() {
    console.log(retreatMessage)
  },
  takeOff() {
    console.log("Spim... Borp... Glix... Blastoff!"")
  }
};

alienShip.retreat();
alienShip.takeOff();

Nested objects:

let spaceship = {
  passengers: [{name: "Space Dog"}, {name: "Space Jeffrold"}],
  telescope: {
    yearBuilt: 2018,
    model: "91031-XLT",
    focalLength: 2032 
  },
  crew: {
    captain: { 
      name: 'Sandra', 
      degree: 'Computer Engineering', 
      encourageTeam() { console.log('We got this!') },
     'favorite foods': ['cookies', 'cakes', 'candy', 'spinach'] }
  },
  engine: {
    model: "Nimbus2000"
  },
  nanoelectronics: {
    computer: {
      terabytes: 100,
      monitors: "HD"
    },
    backup: {
      battery: "Lithium",
      terabytes: 50
    }
  }
}; 

let capFave = spaceship.crew.captain["favorite foods"][0];
let firstPassenger = spaceship.passengers[0];

Passing by reference:

let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
  homePlanet : 'Earth'
};

let greenEnergy = objectParam => {
  objectParam["Fuel Type"] = "avocado oil";
};

let remotelyDisable = objectParam => {
  objectParam.disabled = true;
};

greenEnergy(spaceship);
remotelyDisable(spaceship);
console.log(spaceship);

Finally looping through objects:

let spaceship = {
    crew: {
    captain: { 
        name: 'Lily', 
        degree: 'Computer Engineering', 
        cheerTeam() { console.log('You got this!') } 
        },
    'chief officer': { 
        name: 'Dan', 
        degree: 'Aerospace Engineering', 
        agree() { console.log('I agree, captain!') } 
        },
    medic: { 
        name: 'Clementine', 
        degree: 'Physics', 
        announce() { console.log(`Jets on!`) } },
    translator: {
        name: 'Shauna', 
        degree: 'Conservation Science', 
        powerFuel() { console.log('The tank is full!') } 
        }
    }
}; 

for (let crewMember in spaceship.crew) {
  console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`)
};

for (let crewMember in spaceship.crew) {
  console.log(`${spaceship.crew[crewMember].name}: ${spaceship.crew[crewMember].degree}`)
};

Found today as easy going as yesterday. I feel like everything leading up before objects has tied together nicely today.

3 Likes

Day 12

Using this keyword:

const robot = {
  model: "1E78V2",
  energyLevel: 100,
  provideInfo() {
    return (`I am ${this.model} and my current energy level is ${this.energyLevel}`);
  }
};

console.log(robot.provideInfo());

Arrow notation doesn’t play well with this so it’s good to change this:

const robot = {
  energyLevel: 100,
  checkEnergy: () => {
    console.log(`Energy is currently at ${this.energyLevel}%.`)
  }
}

robot.checkEnergy();

To this:

const robot = {
  energyLevel: 100,
  checkEnergy() {
    console.log(`Energy is currently at ${this.energyLevel}%.`);
  }
}

robot.checkEnergy();

Mutating some a private property to force type-coercion:

const robot = {
  _energyLevel: 100,
  recharge(){
    this._energyLevel += 30;
    console.log(`Recharged! Energy is currently at ${this._energyLevel}%.`)
  }
};

robot._energyLevel = "high";

robot.recharge();

Getters, getting a bit more complicated now:

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  get energyLevel(){
    if (typeof this._energyLevel === "number") {
      return "My current energy level is " + this._energyLevel
    } else {
      return "System malfunction: cannot retrieve energy level"
    }
  }
};

console.log(robot.energyLevel);

Setters, similar to getters:

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  _numOfSensors: 15,
  get numOfSensors(){
    if(typeof this._numOfSensors === 'number'){
      return this._numOfSensors;
    } else {
      return 'Sensors are currently down.'
    }
  },
  set numOfSensors(num) {
    if (typeof num === "number" && num >= 0){
      this._numOfSensors = num;
    } else {
      console.log("Pass in a number that is greater than or equal to 0");
    }   
  } 
};

robot.numOfSensors = 100;
console.log(robot.numOfSensors);

Using a factory function:

const robotFactory = (model, mobile) => {
  return {
    model: model,
    mobile: mobile,
    beep() {
      console.log("beep boop");
    }
  }
};
const tinCan = robotFactory("P-500", true);
tinCan.beep();

Using property value short-hand to change this:

function robotFactory(model, mobile){
  return {
    model: model,
    mobile: mobile,
    beep() {
      console.log('Beep Boop');
    }
  }
}

// To check that the property value shorthand technique worked:
const newRobot = robotFactory('P-501', false)
console.log(newRobot.model)
console.log(newRobot.mobile)

Into this:

function robotFactory(model, mobile){
  return {
    model,
    mobile,
    beep() {
      console.log('Beep Boop');
    }
  }
}

// To check that the property value shorthand technique worked:
const newRobot = robotFactory('P-501', false)
console.log(newRobot.model)
console.log(newRobot.mobile)

They’re really working me hard on that one! :smile:

Using destructured assignment to save keystrokes:

const robot = {
  model: '1E78V2',
  energyLevel: 100,
  functionality: {
    beep() {
      console.log('Beep Boop');
    },
    fireLaser() {
      console.log('Pew Pew');
    },
  }
};

const { functionality } = robot;
functionality.beep();

Ending today’s session by building a new robot!

const robot = {
	model: 'SAL-1000',
  mobile: true,
  sentient: false,
  armor: 'Steel-plated',
  energyLevel: 75
};

// What is missing in the following method call?
const robotKeys = Object.keys(robot);

console.log(robotKeys);

// Declare robotEntries below this line:
const robotEntries = Object.entries(robot);

console.log(robotEntries);

// Declare newRobot below this line:
const newRobot = Object.assign({laserBlaster: true}, {voiceRecognition: true}, robot);

console.log(newRobot);

I’m not sure how much of this I am going to remember but I can always look up documentation for a refresher if needed. Little by little my knowledge is growing and I feel like I can imagine coding properly one day.

2 Likes

Day 13

Today’s class is classes. Creating a class:

class Surgeon {
  constructor(name, department) {
    this.name = name;
    this.department = department;
  }
}

Creating instances:

class Surgeon {
  constructor(name, department) {
    this.name = name;
    this.department = department;
  }
}

const surgeonCurry = new Surgeon("Curry", "Cardiovascular");
const surgeonDurant = new Surgeon("Durant", "Orthopedics");

The site told me I got this code wrong, so I clicked show solution to see what I did differently to them. Turns out they put exactly the same as me except I used " where they use '. That was never a problem before…

Class methods:

class Surgeon {
  constructor(name, department) {
    this._name = name;
    this._department = department;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get department() {
    return this._department;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

const surgeonCurry = new Surgeon('Curry', 'Cardiovascular');
const surgeonDurant = new Surgeon('Durant', 'Orthopedics');

Adding some method calls:

class Surgeon {
  constructor(name, department) {
    this._name = name;
    this._department = department;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get department() {
    return this._department;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

const surgeonCurry = new Surgeon('Curry', 'Cardiovascular');
const surgeonDurant = new Surgeon('Durant', 'Orthopedics');

console.log(surgeonCurry._name);
surgeonCurry.takeVacationDays(3);
console.log(surgeonCurry._remainingVacationDays);

Setting up a parent class for inheritance:

class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }

  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }  
};

Creating a child class:

class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

class Nurse extends HospitalEmployee {
  constructor(name, certifications) {
    super(name);
        super(remainingVacationDays);
    this._certifications = certifications;
  }
}

const nurseOlynyk = new Nurse("Olynyk", ["Trauma", "Pediatrics"]);

Exercise says I did this right, the console however does not like my:

super(remainingVacationDays);

It was not made clear by the course how I should take multiple properties from a parent class. Annoyingly they refuse to show you the solution once you have completed a section. Lucky the next exercise shows me what I should have done and I understand what I did wrong now.

Here’s how it should look along with adding a method call:

class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

class Nurse extends HospitalEmployee {
 constructor(name, certifications) {
   super(name);
   this._certifications = certifications;
 } 
}

const nurseOlynyk = new Nurse('Olynyk', ['Trauma','Pediatrics']);

nurseOlynyk.takeVacationDays(5);
console.log(nurseOlynyk.remainingVacationDays);

Adding unique getters and methods to the child class:

class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

class Nurse extends HospitalEmployee {
  constructor(name, certifications) {
    super(name);
    this._certifications = certifications;
  } 
  
 get certifications() {
   return this._certifications;
 } 
  
  addCertification(newCertification) {
    this._certifications.push(newCertification);
  }
  
}

const nurseOlynyk = new Nurse('Olynyk', ['Trauma','Pediatrics']);
nurseOlynyk.takeVacationDays(5);
console.log(nurseOlynyk.remainingVacationDays);

nurseOlynyk.addCertification("Genetics");
console.log(nurseOlynyk.certifications);

Adding a static method to the HospitalEmployee class:

 static generatePassword() {
    return Math.floor(Math.random() * 10000);
  }

I like classes. I remember reading about how different languages treat inheritance differently; I don’t remember specifics. I like how JavaScript handles it so far though; reminds me of using symbolic logic in philosophy.

3 Likes

Day 14

Learning about browser compatibility.

Starting off by running ES6 code in a fake old browser:

var pasta = "Spaghetti"; // ES5 syntax

const meat = "Pancetta"; // ES6 syntax

let sauce = "Eggs and cheese"; // ES6 syntax

// Template literals, like the one below, were introduced in ES6
const carbonara = `You can make carbonara with ${pasta}, ${meat}, and a sauce made with ${sauce}.`;

Next I have been asked to use caniuse.com to find percentages of features used:

// Percentage browsers that support ES5
let esFivePercentageSupport = 96;

// Percentage browsers that support template literals
let esSixTemplateLiterals = 89;

Changing the code from earlier to meet ES5 compatibility:

var pasta = "Spaghetti"; 

var meat = "Pancetta"; 

var sauce = "Eggs and cheese"; 

var carbonara = "You can make carbonara with " + pasta + ", " + meat + ", and a sauce made with " + sauce + ".";

I installed some babel packages in the terminal window and it transpiled the code. It looks just like mine I did manually but with the //comments still in.

npm init: Node managing stuff. Making a package.json to hold our metadata. This reminds me of making mods for Planetary Annihilation (Just simple map packs). Don’t fancy copying and pasting from the terminal but it was fine.

Now I’m installing packages using the -D flag to add them to devDependencies; using “ls” to check that the node-modules is in the directory.

Using “touch” to create a new .babelrc file. Opened the new file and created an object that specifies the preset as “env”.

Going into the package.json to add a new property; “build”, to the scripts object.

"build": "babel src -d lib"

Finally I “npm run build” to transpile the ES6 code into ES5!

I really liked working with the terminal and looking through the directories. I feel like I have come a long way in the last 2 weeks. I still feel incredibly new but my understanding of how things fit together is growing and my confidence in working with code in the future is improving.

1 Like

Day 15

Creating my first module:

const Airplane = {};
Airplane.myAirplane = "StarJet";
module.exports = Airplane;

Making use of an exported module:

const Airplane = require('./1-airplane.js');
function displayAirplane() {
  console.log(Airplane.myAirplane);
};

displayAirplane();

Course didn’t like me using " so I will try to use ’ from now on. Starting to get a bit confused by the change in syntax with today’s lessons.

Writing this new module from scratch:

const Airplane = {};

module.exports = {
  myAirplane: "CloudJet",
  displayAirplane: function() {
    return this.myAirplane;
  }
};

Exporting it to:

const Airplane = require('./2-airplane.js');
console.log(Airplane.displayAirplane());

Using “export default”:

let Airplane = {};

Airplane.availableAirplanes = [
  {
    name: "AeroJet",
    fuelCapacity: 800
  },
  {
    name: "SkyJet",
    fuelCapacity: 500
  }
];

export default Airplane;

Importing a module to this code:

import Airplane from './airplane';

function displayFuelCapacity() {
  Airplane.availableAirplanes.forEach(function(element){
  console.log('Fuel Capacity of ' + element.name + ': ' + element.fuelCapacity);
  });
}

displayFuelCapacity();

The course basically had to put that all in for me because I had no idea how to do it. I feel like it’s not really explaining syntax as well as it used to and it’s really frustrating.

Named exports:

let availableAirplanes = [{
 name: 'AeroJet',
 fuelCapacity: 800,
 availableStaff: ['pilots', 'flightAttendants', 'engineers', 'medicalAssistance', 'sensorOperators'],
}, 
{name: 'SkyJet',
 fuelCapacity: 500,
 availableStaff: ['pilots', 'flightAttendants']
}];

let flightRequirements = {
  requiredStaff: 4,
};

function meetsStaffRequirements(availableStaff, requiredStaff) {
  if (availableStaff.length >= requiredStaff) {
    return true;
  } else {
    return false;
  }
};

export { availableAirplanes, flightRequirements, meetsStaffRequirements};

My hour is up and I don’t have the patience to continue this exercise for tonight.

3 Likes

Day 16

Starting off the day with named imports:

import {availableAirplanes, flightRequirements, meetsStaffRequirements} from './airplane';

function displayFuelCapacity() {
  availableAirplanes.forEach(function(element) {
    console.log('Fuel Capacity of ' + element.name + ': ' + element.fuelCapacity);
  });
}

displayFuelCapacity();

function displayStaffStatus() {
  availableAirplanes.forEach(function(element) {
   console.log(element.name + ' meets staff requirements: ' + meetsStaffRequirements(element.availableStaff, flightRequirements.requiredStaff) );
  });
}

displayStaffStatus();

Adding more data and exporting variables at the moment of their declaration:

export let availableAirplanes = [{
 name: 'AeroJet',
 fuelCapacity: 800,
  maxSpeed: 1200,
  minSpeed: 300,
 availableStaff: ['pilots', 'flightAttendants', 'engineers', 'medicalAssistance', 'sensorOperators'],
}, 
{name: 'SkyJet',
 fuelCapacity: 500,
 maxSpeed: 800,
 minSpeed: 200,
 availableStaff: ['pilots', 'flightAttendants']
}];

export let flightRequirements = {
  requiredStaff: 4,
  requiredSpeedRange: 700
};

export function meetsSpeedRangeRequirements(maxSpeed, minSpeed, requiredSpeedRange) {
  let range = maxSpeed - minSpeed;
  if (range > requiredSpeedRange) {
   return true;
      } else {
        return false;
      }   
};

export function meetsStaffRequirements(availableStaff, requiredStaff) {
  if (availableStaff.length >= requiredStaff) {
    return true;
  } else {
    return false;
  }
};

Adding a speed range status function:

import {availableAirplanes, flightRequirements, meetsStaffRequirements, meetsSpeedRangeRequirements} from './airplane';

function displayFuelCapacity() {
  availableAirplanes.forEach(function(element) {
    console.log('Fuel Capacity of ' + element.name + ': ' + element.fuelCapacity);
  });
}

displayFuelCapacity();

function displayStaffStatus() {
  availableAirplanes.forEach(function(element) {
   console.log(element.name + ' meets staff requirements: ' + meetsStaffRequirements(element.availableStaff, flightRequirements.requiredStaff) );
  });
}

displayStaffStatus();

function displaySpeedRangeStatus() {
availableAirplanes.forEach(function(element) {
  console.log(element.name + ' meets speed range requirements: ' + meetsSpeedRangeRequirements(element.maxSpeed, element.minSpeed, flightRequirements.requiredSpeedRange) );
}); 
}

displaySpeedRangeStatus();

Removed the previous exports at declared variables in the module and added an export statement at the bottom, making aliases:

export { availableAirplanes as aircrafts, flightRequirements as flightReqs, meetsStaffRequirements as meetsStaffReqs, meetsSpeedRangeRequirements as meetsSpeedRangeReqs };

Modifying the code to import the aliased variables:

import {aircrafts, flightReqs, meetsStaffReqs, meetsSpeedRangeReqs} from './airplane';

function displayFuelCapacity() {
  aircrafts.forEach(function(element) {
    console.log('Fuel Capacity of ' + element.name + ': ' + element.fuelCapacity);
  });
}

displayFuelCapacity();

function displayStaffStatus() {
  aircrafts.forEach(function(element) {
   console.log(element.name + ' meets staff requirements: ' + meetsStaffReqs(element.availableStaff, flightReqs.requiredStaff) );
  });
}

displayStaffStatus();

function displaySpeedRangeStatus() {
aircrafts.forEach(function(element) {
  console.log(element.name + ' meets speed range requirements: ' + meetsSpeedRangeReqs(element.maxSpeed, element.minSpeed, flightReqs.requiredSpeedRange) );
}); 
}

displaySpeedRangeStatus();

Finish up today’s lesson by changing the import and export stuff a load more. Whoever designed this lesson is either an asshole or preparing me for tedious, repetitive alterations of code in the future.

1 Like

I might do one of these but learn Kotlin.

1 Like

I feel unwell :nauseated_face: after a long day of doing real life stuff. I shall make up today’s hour down the road somewhere.

1 Like

Day 17

Constructing promises:

const inventory = {
  sunglasses: 1900,
  pants: 1088,
  bags: 1344
};

// Write your code below:
const myExecutor = (resolve, reject) => {
    if (inventory.sunglasses > 0) {
        resolve('Sunglasses order processed.');
    } else {
        reject('That item is sold out.');
    }
};

const orderSunglasses = () => {
    return new Promise(myExecutor);
};

const orderPromise = orderSunglasses();

console.log(orderPromise);  

setTimeout() function:

console.log("This is the first line code in app.js.");
// Keep the line above as the first line of code
// Write your code here:
const usingSTO = () => {
  console.log("This is a string.");
};

setTimeout(usingSTO, 3000);

// Keep the line below as the last line of code:
console.log("This is the last line of code in app.js.");

onFulfilled and onRejection functions:

const {checkInventory} = require('./library.js');

const order = [['sunglasses', 1], ['bags', 2]];

// Write your code below:
const handleSuccess = (resolvedValue) => {
  console.log(resolvedValue);
};

const handleFailure = (rejectionReason) => {
  console.log(rejectionReason);
};

checkInventory(order)
.then(handleSuccess, handleFailure);

Parent module:

const inventory = {
    sunglasses: 1900,
    pants: 1088,
    bags: 1344
};

const checkInventory = (order) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            let inStock = order.every(item => inventory[item[0]] >= item[1]);
            if (inStock) {
                resolve(`Thank you. Your order was successful.`);
            } else {
                reject(`We're sorry. Your order could not be completed because some items are sold out.`);
            }
        }, 1000);
    })
};

module.exports = { checkInventory };

Using .catch:

const {checkInventory} = require('./library.js');

const order = [['sunglasses', 1], ['bags', 2]];

const handleSuccess = (resolvedValue) => {
  console.log(resolvedValue);
};

const handleFailure = (rejectReason) => {
  console.log(rejectReason);
};

// Write your code below:
checkInventory(order)
	.then(handleSuccess)
	.catch(handleFailure);

Chaining multiple promises:

const {checkInventory, processPayment, shipOrder} = require('./library.js');

const order = {
  items: [['sunglasses', 1], ['bags', 2]],
  giftcardBalance: 79.82
};

checkInventory(order)
.then((resolvedValueArray) => {
  
 return processPayment(resolvedValueArray);
})
.then((resolvedValueArray) => {
  
  return shipOrder(resolvedValueArray);
})
.then((successMessage) => {
  console.log(successMessage);
})
.catch((errorMessage) => {
  console.log(errorMessage);
});

If you’re interested in the parent module they provided for me:

const store = {
  sunglasses: {
    inventory: 817, 
    cost: 9.99
  },
  pants: {
    inventory: 236, 
    cost: 7.99
  },
  bags: {
    inventory: 17, 
    cost: 12.99
  }
};

const checkInventory = (order) => {
  return new Promise ((resolve, reject) => {
   setTimeout(()=> {  
   const itemsArr = order.items;  
   let inStock = itemsArr.every(item => store[item[0]].inventory >= item[1]);
   
   if (inStock){
     let total = 0;   
     itemsArr.forEach(item => {
       total += item[1] * store[item[0]].cost
     });
     console.log(`All of the items are in stock. The total cost of the order is ${total}.`);
     resolve([order, total]);
   } else {
     reject(`The order could not be completed because some items are sold out.`);
   }     
}, generateRandomDelay());
 });
};

const processPayment = (responseArray) => {
  const order = responseArray[0];
  const total = responseArray[1];
  return new Promise ((resolve, reject) => {
   setTimeout(()=> {  
   let hasEnoughMoney = order.giftcardBalance >= total;
   // For simplicity we've omited a lot of functionality
   // If we were making more realistic code, we would want to update the giftcardBalance and the inventory
   if (hasEnoughMoney) {
     console.log(`Payment processed with giftcard. Generating shipping label.`);
     let trackingNum = generateTrackingNumber();
     resolve([order, trackingNum]);
   } else {
     reject(`Cannot process order: giftcard balance was insufficient.`);
   }
   
}, generateRandomDelay());
 });
};


const shipOrder = (responseArray) => {
  const order = responseArray[0];
  const trackingNum = responseArray[1];
  return new Promise ((resolve, reject) => {
   setTimeout(()=> {  
     resolve(`The order has been shipped. The tracking number is: ${trackingNum}.`);
}, generateRandomDelay());
 });
};


// This function generates a random number to serve as a "tracking number" on the shipping label. In real life this wouldn't be a random number
function generateTrackingNumber() {
  return Math.floor(Math.random() * 1000000);
}

// This function generates a random number to serve as delay in a setTimeout() since real asynchrnous operations take variable amounts of time
function generateRandomDelay() {
  return Math.floor(Math.random() * 2000);
}

module.exports = {checkInventory, processPayment, shipOrder};

Using Promise.all():

const {checkAvailability} = require('./library.js');

const onFulfill = (itemsArray) => {
  console.log(`Items checked: ${itemsArray}`);
  console.log(`Every item was available from the distributor. Placing order now.`);
};

const onReject = (rejectionReason) => {
	console.log(rejectionReason);
};

// Write your code below:

const checkSunglasses = checkAvailability('sunglasses', 'Favorite Supply Co.');
const checkPants = checkAvailability('pants', 'Favorite Supply Co.'); 
const  checkBags = checkAvailability('bags', 'Favorite Supply Co.');

Promise.all([checkSunglasses, checkPants, checkBags])
  .then(onFulfill)
  .catch(onReject);

The style of this course is starting to grate on me and I feel like I’m not absorbing a much information as when I started. I have a feeling it’s so they can entice you to subscribe to their “Pro” service that gives you practice exercises to absorb lessons.

1 Like

That’s the nub of it. You have to use the stuff otherwise it doesn’t really sink in and in a month or two it will be all gone!

Any chance you can start working on a project on the side to help reinforce what you are learning?

At the pace I’m currently on I’ll be finished with this course very soon. I’ll likely use the rest of December to do some kind of project to put my knowledge to use.

1 Like

Day 18

I’m stopping this course now. I know I’m near the end but this asynchronous stuff is over my head. I’ve not had time to practice previous work and it’s not sinking in enough for me to move on at this pace. I’m not really sure what to do at this point; I’m thinking put my Devember on hold until the weekend, let my brain cool off and then spend a few hours starting a project on a day I don’t have work.

I did enjoy this course but I really think it is designed to be used with their “pro” lessons. They offered the pro lessons along with the first activities as a taster and they were definitely needed in my opinion, but I don’t think the cost is justified.

Sorry to everyone who has been following so far and if you have any comments/opinions/suggestions please feel free to chime in!