Ironhack Day 17

MongoDB:

0. How to start mongo in the terminal:

a. start_mongo

b. open new tab and type mongo

c. open third tab and node index.js

1. Show me element’s name but not its id:

db.enemies.find({”name”: ”Blinky”}, {name: 1, _id:0})

{ ”name” : ”Blinky” }

2. Show property of an embedded document, notice the use of quotations marks (phone is an embedded document of the employees database, since it has different properties, among them ”ext”):

db.employees.find({”phone.ext”: ”2143”})

3. Updating a document:

db.employees.updateOne(
{ ”name”: ”Martin”},
{ $set: { ”phone.ext”: 1234 }}
)

4. Replacing an object of an array:

var susan = {
”name” : ”Susan”,
”age” : 25,
”phone” : { ”personal” : ”555-223-223”, ”work” : ”555-421-426”, ”ext” : 4240 },
”privileges” : ”user”,
}

db.employees.replaceOne(
{ ”name”: ”Martin”},
susan
)

5a. Deleting one element:

db.employees.deleteOne( { ”_id”: ObjectId(”583ea82c58613b64d5df8405”) })

5b. Deleting several elements:

db.employees.deleteMany({ age : { $gte: 30 }})

5c. Delete all:

db.employees.deleteMany({})

6. Use mongoimport to import documents into a collection:

$ mongoimport –db restaurants –collection restaurants –drop –file ~/downloads/primer-dataset.json

7. The only reason to use the $and operator is to apply more than one condition (that isn’t equality) over the same field:

db.users.find({
$and: [
{”age”: {$gt: 18}},
{”age”: {$lt: 30}}
]
})

OR

db.restaurants.find({
$and: [
{”borough”: ”Brooklyn”},
{”grades.score”: {$gte: 80}}
]
}).pretty()

8. Sorting (note: 1 here is for ascending and -1 for descending order):

db.restaurants.find().sort( { ”borough”: 1, ”address.zipcode”: -1 } )

9a. Counting all the number of documents:

db.restaurants.find().count()

9b. Counting certain documents:

db.restaurants.find({”grades.score”: {$gte: 10}}).pretty().count()

10. Find documents according to their positions in the array (here they are in position two):

db.restaurants.find({”grades.1.grade” : ”A”}).pretty()

9. Example of deleting one document from your Mongo DB:

db.projects.remove( { ”name” : ”bla”})

Ironhack Day 16

ES6

0. ES6 compatibility table: https://kangax.github.io/compat-table/es6/

1.Using classes:

class Product {
constructor (name, price) {
this.name = name;
this.price = price;
}

nameAndPrice () {
console.log(
”The product’s name is: ” + this.name,
”The product’s price is: ” + this.price
);
}
}

const banana = new Product(”Banana”, 2);
banana.nameAndPrice();

2. Inheritance and overwriting methods (see the second nameAndPrice below):

class Product {
constructor (name, price) {
this.name = name;
this.price = price;
}

nameAndPrice () {
console.log(
”The product’s name is: ” + this.name,
”The product’s price is: ” + this.price
);
}
}

class Electronic extends Product {
constructor (name, price, brand) {
super(name, price);
this.brand = brand;
}

nameAndPrice () {
console.log(
”The product’s name is: ” + this.name,
”The product’s price is: ” + this.price,
”and the brand is ” + this.brand
);
}
}

var banana = new Product(”Banana”, 2);
banana.nameAndPrice();

var mac = new Electronic(”Mac”, 200, ”Apple”);
mac.nameAndPrice();

3. If statements and for loops don’t have own scope:

for (var i = 1; i <= 30; i++){
console.log(”Iteration number: ” + i);
}

console.log(”After the loop”, i);
//After the loop 31

4a. Block scoping with let (incorrectly):

for (let i = 1; i <= 30; i++){
console.log(”Iteration number: ” + i);
}

console.log(”After the loop”, i);
//for After the loop: ReferenceError i is not defined

4b. Block scoping with let (correctly):

let name = ”Ironhacker”;

if (true){
let name = ”Ted”;
console.log(”Name inside of if statement: ” + name);
}

console.log(”Name outside of if statement: ” + name);

// Name inside of if statement: Ted
// Name outside of if statement: Ironhacker

5. Although you can’t reassign ’con’, you can still modify its properties:

const TAXES = {
normal: 0.21
}

console.log(TAXES)

TAXES.normal = 0.23

console.log(TAXES)

// { normal: 0.21 }

// { normal: 0.23 }

6. Arrow functions are syntactic sugar over the typical function declaration, with an added bonus: a new function scope is not created:
class Counter {
constructor(){
this.count = 1;
}

countUp(){
setInterval(() => {
console.log(this.count);
this.count++;
}, 1000);
}
}

var myCounter = new Counter();
myCounter.countUp();

Ironhack Week 3

This week everyone’s worked on his/her own project: building a JavaScript/JQuery game of their choise. Even though a week might seem a short time for such a project for someone who was practically thrown into the deep and murky water of web dev just two weeks earlier it felt like a blessing to have time to go thru (many times with the teacher assistant) everything we’ve learned so far and build the game by the book (more or less), i.e. creating a file for the logic of the game and another one for the DOM manipulation, using a constructor in the ”logic file”, using prototypes as well different array methods (splice, sort, pop and _shuffle from LoDash) and manipulating the DOM with JQuery and/or ”pure” JavaScript. Below is the outcome of my project, a game which solves all the problems of the numerous advanced students of Finnish who are dying for revising their sports vocabulary in Finnish ; -)

P.S. I”ve probably never felt so stupid in my entire life like during the first two weeks of this course. Everything we were taught in the morning we had to practice in the afternoon and evening and it’s not only that there was a huge amount of new information to process, but also the exercises we were given were (as I’ve found out later on), to put it mildly, challenging, even for my course mates who have been doing programming much more seriously than myself and for a much longer time. Then came this third week, when I embraced that my web dev knowledge is close to zero and that the last two weeks’ learning material is in an absolute chaos in my head and decided to work my way up from there. With a lot of help from the TA. I’m still useless when it comes to e.g. JavaScript katas used in technical interviews, but hey, I’ve done this project and I more or less understand everything in my code. Except perhaps the part on generating randomly the Finnish word and the English translations so that there would always be different translations on the different cards + that one of the cards contains the right translation. My head is still spinning every time I read that code. Well, that’s how it is right now, but some day, one day…

 

photo of http://bjim-com.stackstaging.com/Memrise-Fin/

Ironhack Day 8

JavaScript:
1. Passing functions into other functions as arguments (i.e. resultFn, which will be ”replaced” in the add() function call by logDone or square):

function add (first, second, resultFn) {
console.log(”Add function started”);
resultFn(first + second);
}

function logDone (num) {
console.log(”I’m done! The result is: ” + num);
}

function square (num) {
console.log(”The square is: ” + num*num);
}

add(2, 3, logDone);
add(2, 3, square);

2. Using functions as variables (here: logDone):

function add (first, second, callbackFunc) {
console.log(first + second);
callbackFunc();
}

var logDone = function() {
console.log(”I’m done!”);
};

add(2, 3, logDone);

3. ’Return’ breaks the flow of the code and returns a value:

var sayHello = function(){
return ”I’m a string”;
console.log(’hello’);

}
console.log(sayHello())
//”I’m a string” (i.e. console.log won’t work, because of breaking the flow of the code with return)

4. Reassigning a variable (console.log will print out 4, because of reassigning var a to 4 inside function inner):

var a = 1;
var b = 2;

function inner() {
a = 4; // not using `var`
var b = 3; // using ’var’ | Shadowing the global variable
}

inner();
console.log(a);
console.log(b);

5a. Because of hoisting when console.logging inside a function the globally defined variable that has been reassigned inside that function we’ll get an ’undefined’ for it:

var name = ”Fer”;

function changeName () {
console.log(”Original name was ” + name);

var name = ”Harry”;
console.log(”New name is ” + name);
}

changeName();
//’Original name was undefined’
//’New name is Harry’

5b. Fixing the ’undefined’ problem mentioned above:

var name = ”Fer”;
console.log(”Original name was ” + name);

function changeName () {

var name = ”Harry”;
console.log(”New name is ” + name);
}

changeName();
//’Original name was Fer’
//’New name is Harry’

6a. When using ’this’ in a function inside a function, ’this’ will refer to the global variable, in this case the var value = 500:

var value = 500;
var obj = {
value: 0,
increment: function() {
this.value++;

var innerFunction = function() {
console.log(this.value);
}

innerFunction(); // Function invocation pattern
}
}
obj.increment(); // Method invocation pattern
//500

6b. Making sure the ’this’ in a function inside a function is referring to the right variable:

var value = 500;
var obj = {
value: 0,
increment: function() {
var that = this;
that.value++;

var innerFunction = function() {
console.log(that.value);
}

innerFunction(); // Function invocation pattern
}
}
obj.increment();
//1

7a. Modifiying with ’apply’ the context to which ’this’ may refer to (here from the object foo to window):

var obj = {
foo: function(a, b, c) {
console.log( arguments );
console.log( this );
}
};

obj.foo(1,2,3);
// ==> [1,2.3]
// ==> obj {}

obj.foo.apply(window, [1,2,3]);
// ==> [1,2.3]
// ==> window {}

7b. Modifiying with ’bind’ the context to which ’this’ may refer to (here from the object foo to window):

var obj = {
foo: function() {
console.log( this );
}
};

var bindFoo = obj.foo.bind(window);

obj.foo(); // ==> obj
bindFoo(); // ==> window

8a. ’this’ is referring to the object AT THE MOMENT OF THE EXECUTION, that’s why in the jQuery code below ’this’ works only when pressed the first time (after that you get undefined):

var dog = {
sound: ”Whoof!!!”,
makeSound: function(){
console.log(this.sound);
}
}
dog.makeSound()

$(’button’).click(dog.makeSound());

8b. Making ’this’ work every time you click the button with the help of ’bind’:

var dog = {
sound: ”Whoof!!!”,
makeSound: function(){
console.log(this.sound);
}
}
dog.makeSound()

$(’button’).click(dog.makeSound.bind(dog));

Ironhack Day 7

JQuery:

1. Preventing default event (in this case the default being the opening of a link when you click it):

$(document).ready(function() {

$(’a’).click(function(event){
event.preventDefault();

alert(”Bye!”);
});

});

2. Selecting DOM elements with JQuery:

$(document).ready(function() {

var container =$(’.container’);
var someId = $(’#someId’)
var menu = $(’.menu’);
console.log(’container ’, container);
console.log(’some Id ’, someId);
console.log(’menu ’, menu);
var menuPlusLi = $(’.menu li’);
console.log(’menuPlusLi’, menuPlusLi);
var menuFirstElement = $(’.menu2 li:first’);
console.log(’menuFirstElement ’, menuFirstElement);

});

3. JQuery cheat sheet: https://oscarotero.com/jquery/

4. Changing the name of a class with JQuery and adding a new class:

console.log(’menu2 class name ’, $(’.menu2’).attr(’class’, ’menu3’));
console.log(’menu2 class name ’, $(’.menu2’).addClass(’newClass’));

Ironhack Day 6

JavaScript

1. Example of using an (anonymous) callback function like setTimeout with an asynchronous method:

function init(){
setTimeout(function(){
console.log(’Hi again!’)
}, 8000)
}

init()
console.log(’Hi!’)

// Hi!
// (after 8 sec) Hi again!

2. Using setInterval with an asynchronous method (it calls a function repeatedly with a fixed delayed time between each call):

var i = 10;
var intervalId = setInterval(function() {
if (i > 0) {
console.log(i);
} else {
console.log(”Pop!”);
clearInterval(intervalId);
}

i–;
}, 1000);

// 10
// 9
// 8 etc.
// Pop!

3. When using prototype it’s the instance of the prototype (here the function Car) that has priority over the prototype itself, that’s why below fiat will be red and not blue:

function Car(){
this.color = ”red”
}

Car.prototype.color = ”blue”

var fiat = new Car()

console.log(fiat.color)

// ’red’

4. To speed up your code it’s better to define properties in the prototype instead of defining them in the constructor (=in the function Car):

function Car(){
//this.color = ”red”

}

Car.prototype.color = ”blue”
Car.prototype.wheelsNum = ”4”

var fiat = new Car()

console.log(fiat.color)

var factory = []

for (var i = 0; i < 100; i++) {
factory.push(new Car(”))
}
console.log(factory)

5. In order to make an object be an instanceof another object you have to use both the .call method and prototype:

function Animal (name, owner, sound) {
this.name = name;
this.owner = owner;
this.sound = sound;
}

function Dog (name, owner){
Animal.call(this, name, owner);
this.sound = ”Guau Guau”;
this.humanRelation = ”love”;
}

Dog.prototype = Object.create(Animal.prototype);

var myAnimal = new Animal(”Arya”, ”Josephine”, ”–”);
var myDog = new Dog(”Max”, ”Owen”);

Bootstrap:
1. Remember to add the jquery cdn at the bottom of your html (see https://code.jquery.com/) before the bootstrap.min.js, like this:

<!– jQuery (necessary for Bootstrap’s JavaScript plugins) –>
    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”></script>
    <!– Include all compiled plugins (below), or include individual files as needed –>
    <script src=”js/bootstrap.min.js”></script>
  </body>
</html>

2. Customizing Bootstrap: http://getbootstrap.com/customize/

3. Alternatives to Bootstrap:
http://materializecss.com
http://foundation.zurb.com

4. Free Bootstrap themes: https://bootswatch.com/

Ironhack Day 5

JavaScript:

1. Use ’this’ e.g. when you want to create new objects based on your function (remember to use ’new’ when creating new objects + the convention is to use capital letters for the name of the function in such cases to show they are classes; classes behave like blueprints, prototypes, etc.: they are there in order to enable you with the help of ’new’ to make as many instances of them as you want):

function Car(name){
this.name = name;
this.sayMyName = function() {
console.log(”This car’s name is ” + this.name);
};
}

var kitt = new Car(”Knight Industries Two Thousand”);
var modelS = new Car(”Tesla Model S SuperCar”);

kitt.sayMyName(); // => My name is Knight Industries Two Thousand
modelS.sayMyName(); // => My name is Tesla Model S SuperCar

2. When invoking a method in an object, ’this’ becomes the object itself:

var kitt = {
name: ’Knight Industries Two Thousand’,
sayMyName: function() {
console.log(”My name is ” + this.name);
}
};

var modelS = {
name: ’Tesla Model S SuperCar’,
sayMyName: function() {
console.log(”My name is ” + this.name);
}
};

kitt.sayMyName();
modelS.sayMyName();

3. Simple multiplying function with ’this’:

function Calculator () {
this.total = 0;
this.multiply = function(first, second) {
this.total = first * second;
console.log(this.total);
};
}

var s = new Calculator();
s.multiply(2,3);

4. Calculator with prototype:

function Calculator(){

this.number1 = 0;
this.number2 = 0;
this.result = 0;

Calculator.prototype.askNumber1 = function(){
this.number1 = parseInt(prompt())
}

Calculator.prototype.askNumber2 = function(){
this.number2 = parseInt(prompt())
}

Calculator.prototype.showResult = function(){
console.log(this.result)
}

Calculator.prototype.add = function(){
this.result = this.number1 + this.number2
}

Calculator.prototype.multiply = function(){
this.result = this.number1 * this.number2
}

Calculator.prototype.substract = function(){
this.result = this.number1 – this.number2
}

Calculator.prototype.divide = function(){
this.result = this.number1 / this.number2
}
}
Calculator.prototype.add = function() {
this.result
}
var calc = new Calculator()

calc.askNumber1();
calc.askNumber2();
calc.add();
calc.showResult();

5. Link to DOM (Document Object Model) properties: https://developer.mozilla.org/en-US/docs/Web/API/Document#Properties

6. Link to DOM methods: https://developer.mozilla.org/en-US/docs/Web/API/Document#Methods

Ironhack Day 4

JavaScript:

map is very similar to forEach (both are used to process arrays), except that forEach simply iterates over an array and allow us to do something with each element, while map iterates over an array, BUT returns a new array where each element of the new array is. Examples:

1a. Map:
var array = [1, 2, 3];

var newArray = array.map(function(number){
return number * 2;
})

console.log(newArray);
// [ 2, 4, 6 ]

1b. To achieve the same thing with forEach, you need a longer code:

var array = [1, 2, 3];
var newArray = [];

array.forEach(function(number){
newArray.push(number * 2);
})

console.log(newArray);
// [ 2, 4, 6 ]

2. Another example of using map (turning the first letters of an array’s elements into capital letters):

var cities = [”miami”, ”barcelona”, ”madrid”];

var capsCities = cities.map(function(city){
return city.charAt(0).toUpperCase() + city.slice(1);
})

console.log(capsCities);
// [”Miami”, ”Barcelona”, ”Madrid”]

3a. Using .reduce to get the sum of a number array + print also currentIndex and the array:

var numbers = [2, 4, 6, 8];

var total = numbers.reduce(function(previous, current, currentIndex, originalArray){
console.log(previous, current, currentIndex, originalArray);
return previous + current;
}, 0);

console.log(total);
// 20

3b. Using .reduce to get the sum of a number array:

var numbers = [2, 4, 6, 8];

var total = numbers.reduce(function(previous, current){
/*console.log(previous, current);*/
return previous + current;
}, 0);

console.log(total);
// 20

4a. Calculate the sum of an array’s objects’ properties (like age of persons) using .reduce:

var people = [
{ name: ”Candice”, age: 25 },
{ name: ”Tammy”,   age: 30 },
{ name: ”Allen”,   age: 49 },
{ name: ”Nettie”,  age: 21 },
{ name: ”Stuart”,  age: 17 }
];

var ages = people.reduce(function(sum, person){
return sum + person.age;
}, 0);

console.log(ages);
// 142

4b. Calculate the sum and average of an array’s objects’ properties using .reduce:

var menu = [
{ name: ”Carrots”, calories: 150 },
{ name: ”Steak”, calories: 350 },
{ name: ”Broccoli”, calories: 120 },
{ name: ”Chicken”, calories: 250 },
{ name: ”Pizza”, calories: 520 }
];

var totalCalories = menu.reduce(function(previous, current){
return previous + current.calories;
}, 0);

var averageCalories = totalCalories / menu.length;
console.log(averageCalories);
// 278

5. Using forEach to calculate sum of elements in an array:

var numbers = [1, 2, 3, 4];
var total = 0

numbers.forEach(function(number){
total += number;
})

console.log(total);
// 10

6. Find certain elements in an array with .filter:

var numbers = [1, 2, 3, 4, 5, 6];

var evens = numbers.filter(function(number){
return number % 2 === 0;
});

console.log(evens);
// [ 2, 4, 6 ]

7a. Sorting an array’s elements in numerical order from lowest to highest:

var numbers = [22, 23, 99, 68, 1, 0, 9];

console.log(numbers.sort());
// [ 99, 68, 23, 22, 9, 1, 0 ]

7b. Sorting an array’s elements in numerical order from highest to lowest:

var numbers = [22, 23, 99, 68, 1, 0, 9];

numbers.sort(function(a, b){
// switch the order of the comparison
return b – a;
});

console.log(numbers);
// [ 99, 68, 23, 22, 9, 1, 0 ]

8. The thisIsMyCB function below is called a callback or higher order function, i.e. you pass a function as an argument and use it inside the other function (more about callback functions: http://callbackhell.com):

function main(thisIsMyCB){
var something = ”bla”;
thisIsMyCB(something);
}

main(function(something){ /*FUNCTION HERE REFERS TO thisIsMyCB*/
console.log(”I’m anonymous ” + something)
})

9. Sort string array alphabetically:

var words = [”Hello”, ”Goodbye”, ”First”, ”A”, ”a”, ”Second”, ”Third”];

words.sort()

console.log(words);

10. Sort string array in descending alphabetical order:

var words = [”Hello”, ”Goodbye”, ”First”, ”A”, ”a”, ”Second”, ”Third”];
words.sort(function(a, b){
if (a > b){ return -1; }
if (a < b){ return 1; } return 0; }); console.log(words); 11. Sort string array by length: var words = [”Hello”, ”Goodbye”, ”First”, ”A”, ”a”, ”Second”, ”Third”]; words.sort(function(a, b){ if (a.length > b.length){ return -1; }
if (a.length < b.length){ return 1; }
return 0; });
console.log(words);
//[ ’Goodbye’, ’Second’, ’Hello’, ’First’, ’Third’, ’A’, ’a’ ]

12. Lodash JS library: https://lodash.com/docs/

Ironhack Day 3

Thought of the day: huge amount of new things to process, not much time to digest them.

My notes from the class:

JavaScript:

1. In order to assign the property of an object to a variable you have to use bracket notation, e.g.:

var columns = {
left: true,
center : false,
right : false
}
var side = columns[’left’];
console.log(side);

2. Accessing properties of an object example 1:

var user = {
name: ”snoopy”,
age: 25,
size: ”small”,
toys: [”bone”, ”ball”],
address: {
street: ”bla”,
number: 23
}
}

console.log(user.toys[1]);
console.log(user.address)
console.log(user.address.street)

Accessing properties of an object example 2:

var book1 = { title: ”The Catcher in the Rye”, author: ”J.D Salinger”, isbn: ”0316769487”, category: ”Classic Literature” };
var book2 = { title: ”To Kill a Mockingbird”, author: ”Harper Lee”, isbn: ”0446310786”, category: ”Classic Literature” };

var library =[book1, book2]
console.log(library[1].title)

3. Accessing properties of an object containing an array:

var library= [
{ title: ”The Catcher in the Rye”, author: ”J.D Salinger”, isbn: ”0316769487”, category: ”Classic Literature” },
{ title: ”To Kill a Mockingbird”, author: ”Harper Lee”, isbn: ”0446310786”, category: ”Classic Literature” }
]

console.log(library[0].title)

4. If you use an array inside an object instead of an object inside an object it will be easier to access the respective properties. Example:

var classRoom = {
teacher: { firstName: ’Marcelino’, lastName: ’Padberg’, age: 25 },
students: [
{ firstName: ’Aliyah’, lastName: ’Schulist’, age: 18 },
{ firstName: ’Cleveland’, lastName: ’Towne’, age: 28 },
{ firstName: ’Jan’, lastName: ’Quitzon’, age: 18 },
{ firstName: ’Alaina’, lastName: ’Runolfsdottir’, age: 18 },
{ firstName: ’Gerhard’, lastName: ’Bergstrom’, age: 23 }
]
};

console.log(classRoom.students[2].firstName);
// ’Jan’

console.log(classRoom.teacher.age);
// 25

CSS:

1. Something I didn’t know about advanced selectors:

advanced selectors in css

2. Useful site if planning to use transitions: http://cubic-bezier.com/

3. If planning to do css animations, you might find this site useful: https://daneden.github.io/animate.css/

4. For inspiration on how to use keyframes for css animations check e.g. https://codepen.io/tag/keyframes/