Week 2 & 3 (beginning 17th January) Cycle 3 Covid strikes again! Homeschooling this week - emcsquared2/2022-Learning GitHub Wiki

Week 2 & 3 (Beginning Jan 17th) Learning Week Cycle 3

I won't get as much done this week because of homeschooling but want to grab an hour a day if I can to keep me learning.

Code Signal

Given an integer n, return the largest number that contains exactly n digits.

Example

For n = 2, the output should be solution(n) = 99.

My Solutions

I was really happy with myself for doing this. I did it straight away in a couple of minutes with only one error which was to say i=n instead of i<=n. I realised as my terminal was doing funny things in nodemon so I guessed it was probably an infinite loop or break or something similar.

function solution(n) {
let nineStr = '';
for (let i=1; i<=n; i++){
    nineStr += '9';
};
return +nineStr;
};

GCSE Computer Science

The use of records to store data

Takeaway learning

The contents of variables can be copied from the RAM (temporary and volatile memory) to the permanent memory in a txt file. The program can use the data again later. Simple text files are useful for small amounts of data storage when a program is not running e.g. a game configuration file. Structured data and records can also be loaded and stored in arrays or lists. Access to the data stored in RAM is fast. Only one computer can access at a time. Exernal databases are used to store large volumes of data and can be manipulated using database languages such as SQL. Many users can access the data at the same time. Data in databases is stored records and each record contains a number of fields. Each field can have it's own data type.


MIMO mobile app

ES6 Template Literals Classes

Takeaway learning

When calling a function with a string literal argument you can leave out the brackets and just use the back ticks

const likedBy = person =>{
return `Movie liked by: ${person}`;
}
console.log(likedBy`hellen`)
//Create a new class called Book (the Book name has a capital letter)
class Book {
};

//To create a new object, the class needs a method called constructor().  This sets the property values for new objects.
class Book {
constructor(){
}
};

//To set the values of the new object we send parameters to the constructor method 
class Book {
constructor(author, title){
}
};

//To create a new object property we need to use this keyword
class Book {
constructor(author, title){
  this.author = author; //this.author creates the property author which is set to the parameter value author that will be passed in
  this.title = title;  
}
};

//To use the class we declare a new variable
var book1 = new Book("Leo Tolstoy", "War and Peace");

console.log(book1);
//OUTPUT Book { author: 'Leo Tolstoy', title: 'War and Peace' }

Professor Steve

Manipulating and Sorting Arrays

Takeaway learning

.splice method (starting indice, number of elements to delete, replacing elements)

const fruit = ["banana", "lemon", "apple", "orange"];

fruit.splice(1,2,"plum","mango")

console.log(fruit)

Sorting Arrays .reverse method

const fruit = ["banana", "lemon", "apple", "orange"];

fruit.reverse()
console.log(fruit)
//OUTPUT [ 'orange', 'apple', 'lemon', 'banana']

.sort method

const fruit = ["banana", "lemon", "apple", "orange"];
fruit.sort()

console.log(fruit)
//OUTPUT [ 'apple', 'banana', 'lemon', 'orange' ]

Finding the position of an item in an Array

const fruit = ["banana", "lemon", "apple", "orange", "lemon"];

console.log(fruit.indexOf("lemon"));
console.log(fruit.lastIndexOf("lemon"));

//OUTPUT 1
//OUTPUT 4

Codewars Exercise (Level 8)

Convert number to reversed array of digits. Really happy with the speed at which I can get these done now. This time a year ago this would have been painful.

My Solution

// I had to quickly google how to convert an integer to a string but otherwise this felt very straight forward.

function digitize(n) {
    return n.toString().split("").map(e => +e).reverse()
  }


//A couple of other solutions with slight variations...

function digitize(n){
  return (n + '').split('').map(Number).reverse();
}

function digitize(n) {
  return String(n).split('').map(Number).reverse()
}


//Refreshed my memory of getting the syntax correct when not using the arrow function in the .map function...

function digitize(n) {
    return n.toString().split("").map(function(e) { return +e}).reverse()
  }

JS Practice

Determine if a number is perfect, abundant, or deficient based on Nicomachus' (60 - 120 CE) classification scheme for positive integers.

My solution

This was a really great exercise. The algorithm itself was fairly straight forward but using the CLI and trying to work out what was going on with the testing was a challenge. It kept skipping some of the tests so I wasn't sure if I had done something wrong. And also it was the first time I had to pay attention to where the throw new Error ('bla bla bla') should sit. I decided to put in my first mentoring request which was really helpful. I got a hint which meant if I went into the test file and changed xtest to test it would not skip the test and actually run it. I was also encouraged to factor out a separate function which I named aliquotSum instead of doing everything all in one big function. The reason for this was given in a really helpful video about abstraction.

function aliquotSum(n){
    let sum = 0;
        for (let i=1; i<n; i++){
            if (n%i === 0){
                sum += i;
            }
        };
        console.log(sum)
        return sum
    };
    
function classify(n){

    let sum = aliquotSum(n)      
 
    if (n<1 || n===undefined) {
        console.log ("Classification is only possible for natural numbers.");
    }
    if (sum===n){
        return "perfect";
    } else if(sum<n){
        return "deficient";
    } else if (sum>n){
        return "abundant";
    } 
    };
    console.log(classify(28))

Further feedback to only use 2 conditionals instead of 3. So I used ternary operator and cut it down...

 return sum===n ? "perfect": (sum<n ? "deficient": "abundant") 

Further feedback about making the code easy to read for others and thinking about how a human would think about things normally.

if (sum>n){
        return "abundant";
    } else if(sum<n){
        return "deficient";
    } else {
        return "perfect";
    } 

Further feedback about not running unnecessary code if the n<1 condition is not met. This has been super helpful because I've gone through a phase of learning new concepts and have forgotten about neatness, readability and efficiency. I will definitely reflect on these things and look to implement going forward.

function aliquotSum(n){
    let sum = 0;
        for (let i=1; i<n; i++){
            if (n%i === 0){
                sum += i;
            }
        };
        return sum
    };

export const classify = (n) => {

if (n<1) {
  throw new Error('Classification is only possible for natural numbers.');
}

let sum = aliquotSum(n);

if (sum>n){
    return "abundant";
} else if (sum<n){
    return "deficient";
} else {
    return "perfect";
} 
};

Final iteration to tidy up tabs and spacing

//The purpose of this code is to determine if a number is abundant, defiicient or a perfect number.
//The aliquotSum function takes all the factors of a given number (n) and adds them up in the sum variable 
//(excluding the number itself) 
function aliquotSum(n){
  let sum = 0;
    for (let i=1; i<n; i++){
        if (n%i === 0){
            sum += i;
        }
    };
    return sum;
};

//The number (n) must be greater than or equal to 1.
export const classify = (n) => {
if (n<1) {
  throw new Error('Classification is only possible for natural numbers.');
}

//If the sum of the factors is greater than the number itself it is said to be abundant.
//If the sum is less than n, it will be deficient.
//Equal to is a perfect number
let sum = aliquotSum(n);

if (sum>n){
    return "abundant";
} else if (sum<n){
    return "deficient";
} else {
    return "perfect";
} 
};

Udacity (Object Orientated JavaScript - Free Course)

Takeaway learning

When a regular function is invoked, the value of "this" is the global "window" object. The window object is provided by the browser and is not part of the JavaScript language or specification. Every variable declaration that is made at the global level (outside of a function) automatically becomes a property on the window object!

var currentlyEating = 'ice cream';

window.currentlyEating === currentlyEating
// true

Only declaring variables with the var keyword will add them to the window object. If you declare a variable outside of a function with either let or const, it will not be added as a property to the window object. ``js let currentlyEating = 'ice cream';

window.currentlyEating === currentlyEating // false!

Global Functions are Methods on window

```js
function learnSomethingNew() {
  window.open('https://www.udacity.com/');
}

window.learnSomethingNew === learnSomethingNew
// true

Avoid Globals

  • Tight coupling e.g. global variables being changed could interfere with functions that rely on them if not updated.
  • Name Collisions: A name collision occurs when two (or more) functions depend on a variable with the same name.

Code Signal

n children have got m pieces of candy. They want to eat as much candy as they can, but each child must eat exactly the same amount of candy as any other child. Determine how many pieces of candy will be eaten by all the children together. Individual pieces of candy cannot be split.

My Solutions

Too easy!

const solution = (n, m)=> m - m%n;