Week 4 (Beginning Jan 31st & 7th Feb) Learning Week Cycle 6 - emcsquared2/2022-Learning GitHub Wiki

Week 4 (Beginning Jan 31st) - Learning Week Cycle 6

GCSE Computer Science

How to use subprograms

Takeaway learning

There are two main types of subprograms

  1. Procedures
  • Carry out a task
  • Provide structure
  1. Functions
  • Carry out a task AND return a value
  • Create reusable program components

MIMO mobile app

Extending Classes (inheritance)

Takeaway learning

To inherit features from a class we use the extends keyword in the class definition...

class Animal = {
  constructor(name) {
     this.name = name;
  }
 }

class Dog extends Animal {
}

Dog becomes a subclass of the Animal class(superclass).


Professor Steve

for...in Loops While and Do...While Loops

Takeaway learning

for (let prop in object){
console.log(prop)
}
//OUTPUT lists the keys

for (let prop in object){
console.log(object[prop])
}
//OUTPUT lists the values
//NOTE we cannot use object.prop or object["prop"] because we are only using prop as a variable
//prop is the container to hold each of the values instead of i as the counter in an array for loop

Can also use the for...in loop in Arrays

for (animal in arr){
  console.log("At index", animal, "we have", arr[animal])
 }

//OUTPUT 
//At index 0 we have cat
//At index 1 we have Dog
//At index 2 we have snake

 //OR console.log(`At index ${animal} we have ${arr[animal]}`)
let total = 0;

while( total < 30){
   total += Math.floor(Math.random() * 5) + 1
   console.log(total)
}

/*OUTPUT
3
8
10
15
18
21
23
28
30
*/


let total = 30;
do {
   total += Math.floor(Math.random() * 5) + 1
   console.log(total)
} while( total < 30)
  
//OUTPUT 
//33

// The do bit always happens once

Codewars Exercise (Level 8)

You have to do God's job.
The creation method must return an array of length 2 containing objects (representing Adam and Eve).
The first object in the array should be an instance of the class Man.
The second should be an instance of the class Woman.
Both objects have to be subclasses of Human.
Your job is to implement the Human, Man and Woman classes.

My Solution

This was pretty tricky for a level 8 and I wasn't super clear on the question.
After spending a while on it....

class Human {
  constructor(name){
    this.name = name
  }
};

class Man extends Human{
};

class Woman extends Human{
};

var newMan = new Man("Adam");
var newWoman = new Woman("Eve");

const humans = []

class God {
  static create (){
  humans.push(newMan);
  humans.push(newWoman);
  return humans
  }
};

console.log(God.create())
//OUTPUT [ Man { name: 'Adam' }, Woman { name: 'Eve' } ]

Hurray but not quite
It didn't pass. I think it probaly should have done but anyway.

A better solution...

class Human {};
class Man extends Human{};
class Woman extends Human{};


class God {
  static create (){
    return [new Man, new Woman]
};
};

console.log(God.create())

//OUTPUT [ Man {}, Woman {} ]

JS Practice

Instructions Given a moment, determine the moment that would be after a gigasecond has passed.

A gigasecond is 10^9 (1,000,000,000) seconds.

Notes The input and output of the gigasecond function is of type Date.

My solution

I quickly learnt that I didn't really understand the ins and outs of the Date() object and timestamp.
Professor!


Professor Steve

TIMESTAMPS

Date.now() vs date.valueOf()
In JS timestamp is the number of milliseconds past since January 1, 1970 12:00:00

The parent object (built in JS object - not the class) has a method called now.

let timestamp1 = Date.now()  //class method or static method or prototype method
log(timestamp1);
//OUTPUT 1644313169049

If you have a date object and you've used the constructor method, you get the current time on the computer.

let today = new Date();
log(today)
//OUTPUT 2022-02-08T09:45:29.931Z

Since we have an instance of the Date object, we can extract the current timestamp from it.

let today = new Date();
let timestamp2 = today.valueOf();    //instance method (because we created an instance of the date and asked it for the timestamp)
log(timestamp2)
//OUTPUT 1644314548298

Can also use unary method + to convert a Date into a timestamp. Stick the plus in front of the date variable or new Date()

Date Object

let log = console.log;

let d = new Date(1600000000000);
//The time stamp that was 1.6 trillion milliseconds from the Unix Epoch
log(d)
// 2020-09-13T12:26:40.000Z

let str = '20 July 2010'
let d1 = new Date(str);
log(d1)
//2010-07-19T23:00:00.000Z
//No time was provided
//This has been converted from where I am locally to a UTC value
//This is the same as GMT which is why it hasn't change because my computer is in the UK.

let d2 = new Date(2017, 0, 1, 12, 30, 0, 123)
log(d2)

//2017-01-01T12:30:00.123Z
//If this was a foreign computer abroad it would show a time difference
let d = new Date();

//SET METHODS
d.setFullYear(2020)
log(d)
//OUTPUT 2020-02-08T21:25:58.296Z

//Other set methods setMinutes(), setMonth(), setDate()

//GET METHODS

let t = d.getMinutes();
log(t)
// 28
//other get methods same as set methods i.e. getMonth, getDate
//But also in addtion...

log(d.toDateString())
//Sun Feb 09 2020

log(d.toTimeString())
//08:34:09 GMT+0000 (Greenwich Mean Time)

log(d.toISOString())
//2020-02-09T08:35:13.800Z

log(d.toJSON())
//Date for use in JSON
//2020-02-09T08:36:17.178Z

log(d.toUTCString())
// Sun, 09 Feb 2020 09:14:52 GMT
#### Different Time Zones
log(d.toLocaleString())
// 09/02/2020, 09:09:15


log(d.toLocaleString('en-US'))
// 2/9/2020, 9:08:48 AM


log(d.toLocaleString('en-GB'))
// 09/02/2020, 09:10:50

log(d.toLocaleString('ko-KR'))
// 2020. 2. 9. 오전 9:11:24


log(d.toLocaleString('ar-EG'))
// ٩‏/٢‏/٢٠٢٠ ٩:١٢:٣٤

BACK TO JS Practice!

Instructions
Given a moment, determine the moment that would be after a gigasecond has passed.
Got it right first time!

const gigasecond = (moment) => {
  let addGs = +moment + (1000000000*1000)
  return new Date(addGs)
};
//can also use moment.valueOf()

console.log(gigasecond(new Date(Date.UTC(2011, 3, 25))))

// 2043-01-01T01:46:40.000Z

Recommended improvement...
Rewrite the literal 1000000000*1000 using Math.pow or 10 ** n in order to make its value easier to comprehend.

const gigasecond = (moment) => {
  let addGs = +moment + (Math.pow(10,9)*1000)
  return new Date(addGs)
};

//can also use moment.valueOf()

Next recommended improvement...
Consider extracting the GIGASECOND number into a constant:

const gsInMinutes = (Math.pow(10,9)*1000);

const gigasecond = (moment) => {
  let addGs = +moment + gsInMinutes;
  return new Date(addGs)
};

//can also use moment.valueOf()

Udacity (Object Orientated JavaScript - Free Course)

Takeaway learning

Callback Functions

A function that takes other functions as arguments (and/or returns a function,
as we learned in the previous section) is known as a higher-order function.
A function that is passed as an argument into another function is called a callback function.

function callAndAdd(n , callbackFunction){
  return n + callbackFunction();
}

function returnsThree() {
  return 3;  
}

console.log(callAndAdd(2 , returnsThree))
//OUTPUT is 5

//We are invoking callAndAdd and passing the integer 2 and the callback function into it
function each(array, callback) {
  for (let i = 0; i < array.length; i++) {
    if (callback(array[i])) {
      console.log(array[i]);
    }
  }
}

function isPositive(n) {
  return n > 0;
};

console.log(each([-1,-4,3,9,-8],isPositive))

//OUTPUT
//3
//9
//undefined

Array methods as Callback Functions

[1, 5, 2, 4, 6, 3].forEach(function logIfOdd(n) {
  if (n % 2 !== 0) {
    console.log(n);
  }
});

//The above uses a function declaration
//It's common to use an anonymous function...

[1, 5, 2, 4, 6, 3].forEach(function (n) {
  if (n % 2 !== 0) {
    console.log(n);
  }
});

//or using arrow notation...

[1, 5, 2, 4, 6, 3].forEach(n => {
  if (n % 2 !== 0) {
    console.log(n);
  }
});


//Or just pass in the function name
function logIfOdd(n) {
  if (n % 2 !== 0) {
    console.log(n);
  }
}
[1, 5, 2, 4, 6, 3].forEach(logIfOdd) 

forEach method

/* Using map()
 *
 * Using the musicData array and map():
 *   - Return a string for each item in the array in the following format:
 *     <album-name> by <artist> sold <sales> copies
 *   - Store the returned data in a new albumSalesStrings variable
 *
 * Note:
 *   - Do not delete the musicData variable
 *   - Do not alter any of the musicData content
 *   - Do not format the sales number; leave it as a long string of digits
 */

const musicData = [
    { artist: 'Adele', name: '25', sales: 1731000 },
    { artist: 'Drake', name: 'Views', sales: 1608000 },
    { artist: 'Beyonce', name: 'Lemonade', sales: 1554000 },
    { artist: 'Chris Stapleton', name: 'Traveller', sales: 1085000 },
    { artist: 'Pentatonix', name: 'A Pentatonix Christmas', sales: 904000 },
    { artist: 'Original Broadway Cast Recording', 
      name: 'Hamilton: An American Musical', sales: 820000 },
    { artist: 'Twenty One Pilots', name: 'Blurryface', sales: 738000 },
    { artist: 'Prince', name: 'The Very Best of Prince', sales: 668000 },
    { artist: 'Rihanna', name: 'Anti', sales: 603000 },
    { artist: 'Justin Bieber', name: 'Purpose', sales: 554000 }
];

const albumSalesStrings = musicData.map(function(n){
    return n.name + " by " + n.artist + " sold " + n.sales + " copies"
});

console.log(albumSalesStrings);

/*
[ '25 by Adele sold 1731000 copies',
  'Views by Drake sold 1608000 copies',
  'Lemonade by Beyonce sold 1554000 copies',
  'Traveller by Chris Stapleton sold 1085000 copies',
  'A Pentatonix Christmas by Pentatonix sold 904000 copies',
  'Hamilton: An American Musical by Original Broadway Cast Recording sold 820000 copies',
  'Blurryface by Twenty One Pilots sold 738000 copies',
  'The Very Best of Prince by Prince sold 668000 copies',
  'Anti by Rihanna sold 603000 copies',
  'Purpose by Justin Bieber sold 554000 copies' ]
*/

Code Signal

Using the bike's timer, calculate the current time. Return an answer as the sum of digits that the digital timer in the format hh:mm would show.

For n = 808, the output should be solution(n) = 14.

808 minutes mean that it's 13:28 now, so the answer should be 1 + 3 + 2 + 8 = 14.

My Solutions

function solution(n) {
let sum = 0;
let numString = "";
const hoursStr = "" + Math.floor(n/60);
const minutesStr = "" + n%60;
numString += hoursStr + minutesStr;

for(char of numString){
  sum += +char;
};

 return sum;
};

console.log(solution(808))

A more efficient way of doing this without having to convert from strings to integers is to remember that
you can get the first digit of a number by dividing by 10 and rounding down

function solution(n) {
  const hours = Math.floor(n/60);
  const minutes = n%60;
  return Math.floor(hours/10) + hours%10 + Math.floor(minutes/10) + minutes%10
  };
  
  console.log(solution(808))
⚠️ **GitHub.com Fallback** ⚠️