Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
106 changes: 106 additions & 0 deletions exercises/032-javascriptObjects/README.es.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# `032` JavaScript Objects

A menudo te encontrarás queriendo guardar más información en menos espacio, especialmente si está toda relacionada.

Por ejemplo, digamos que queremos representar autos dentro de variables:

```js
let car1Model = "Corolla";
let car1Make = "Toyota";
let car1Color = "green";
let car1Year = 2015;

let car2Model = "Santa Fe";
let car2Make = "Hyundai";
let car2Color = "purple";
let car2Year = 2013;

//... (¿entiendes la idea?)
```


Hay un enfoque óptimo para esto, son los **objetos**. Los **objetos (objects)** son un tipo de variable que contienen información (otras variables) en forma de `key:value`.

Entonces, si queremos traducir (y optimizar) las variables desde car (auto) a un Object, hacemos:

```js
const car1 = {model: "Corolla", make: "Toyota", color: "green", year: 2015};
```

Puedes ver el `key:value` separado por una coma.

Y para que nosotros (los desarrolladores) podamos leerlas más fácilmente las escribimos así:

```js
const car1 = {
model: "Corolla",
make: "Toyota",
color: "green",
year: 2015
};
```

Parece una función, ¿verdad? Pero no lo es.

Ahora estamos guardando información de una forma más organizada, y si queremos obtener esa información podemos hacer:

```js
console.log(car1.model); //imprime el modelo de car1 en la consola
```

Podemos tener todos los tipos de variables conocidas en JavaScript como valor(`value`) de cualquier `key` (¡incluyendo objetos!). Ahora imagina las posibilidades...

```js
var person = {
name: "John", //String
lastName: "Doe",
age: 35, //Número
gender: "male",
luckyNumbers: [7, 11, 13, 17], //Array
significantOther: person2 //Objeto, sí, la misma variable/objeto definida después
};

var person2 = {
name: "Jane",
lastName: "Doe",
age: 38,
gender: "female",
luckyNumbers: [2, 4, 6, 8],
significantOther: person
};

var family = {
lastName: "Doe",
members: [person, person2] //Array de objetos
};
```

Entonces, si en este escenario queremos saber el nombre del primer miembro de la familia Doe, decimos:

```js
console.log(family.members[0].name);
```

O el 3er número de la suerte del `significantOther` del segundo miembro de la familia Doe:

```js
console.log(family.members[1].significantOther.luckyNumbers[2]);
```

Cosas sencillas :)

## 📝 Instrucciones:

1. De forma automatizada, cambia el cuarto número de la suerte de John Doe (`luckyNumber`) a `33` (usa un comando, no cambies manualmente el código).

2. De forma automatizada, crea una nueva persona y añádela al objeto familia. `Jimmy Doe`, `13`, `male`(masculino), `luckyNumbers` (números de la suerte): `1`, `2`, `3`, `4`; `significantOther: null`.

3. Ahora por favor imprime (`console.log()`) la SUMA de todos los números de la suerte (`luckyNumbers`) de la familia Doe.

## 💡 Pistas:

+ Puedes obtener cada array de números de la suerte (`luckyNumbers`) desde el objeto de cada persona dentro del objeto familia.

+ Una vez obtengas cada array, solo has un loop sobre él sumando cada elemento (como hemos hecho hasta ahora). Luego obtén el total de la suma de los 3 miembros de la familia.

+ `null` también es un objeto.
103 changes: 103 additions & 0 deletions exercises/032-javascriptObjects/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# `032` JavaScript Objects

Often you'll find yourself wanting to save more information in less space, especially if it's all related.

For example, let's say that we want to represent cars into variables:

```js
let car1Model = "Corolla";
let car1Make = "Toyota";
let car1Color = "green";
let car1Year = 2015;

let car2Model = "Santa Fe";
let car2Make = "Hyundai";
let car2Color = "purple";
let car2Year = 2013;

//... (you get the idea)
```

There's an optimized approach to this, it is called **Objects**. **Objects** are a type of variable that contains information (other variables) in a **key:value** manner.

So if we want to translate (and optimize) the variables from the car into an Object, we do:

```js
const car1 = {model: "Corolla", make: "Toyota", color: "green", year: 2015};
```

You can see the `key:value` separated by a comma. And for us (developers) to read it easier we write it like this:

```js
const car1 = {
model: "Corolla",
make: "Toyota",
color: "green",
year: 2015
};
```

Looks like a function, right? But it's not.

Now we are storing information in a more organized way, and if we want to get that information we can do:

```js
console.log(car1.model); //prints the model of car1 in the console
```

We can have all of the known types of variables defined as the value of any `key` (including objects!). Now imagine the possibilities...

```js
var person = {
name: "John", //String
lastName: "Doe",
age: 35, //Number
gender: "male",
luckyNumbers: [7, 11, 13, 17], //Array
significantOther: person2 //Object, yes, the same variable/object defined after
};

var person2 = {
name: "Jane",
lastName: "Doe",
age: 38,
gender: "female",
luckyNumbers: [2, 4, 6, 8],
significantOther: person
};

var family = {
lastName: "Doe",
members: [person, person2] //Array of objects
};
```

So, in this scenario if we want to know the name of the first member of the Doe family we do:

```js
console.log(family.members[0].name);
```

Or the 3rd lucky number of the `significantOther` of the second member of the Doe family:

```js
console.log(family.members[1].significantOther.luckyNumbers[2]);
```

Easy stuff :)

## 📝 Instructions:

1. Programmatically, change the fourth `luckyNumber` of John Doe to `33` (use a command, don't manually change the code).

2. Programmatically, create a new person and add it to the family object. `Jimmy Doe`, `13`, `male`, `luckyNumbers`: `1`, `2`, `3`, `4`; `significantOther: null`.

3. Now please print (`console.log()`) the SUM of all the `luckyNumbers` of the Doe family.

## 💡 Hint:

+ You can get each array of `luckyNumbers` from each person object inside the family object.

+ Once you get each array, just loop over it adding every element (like we've been doing so far). And then add each sum of the 3 family members.

+ `null` is also an object.
38 changes: 38 additions & 0 deletions exercises/032-javascriptObjects/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
var person = {
name: "John", //String
lastName: "Doe",
age: 35, //Number
gender: "male",
luckyNumbers: [7, 11, 13, 17], //Array
significantOther: person2 //Object, yes, the same variable/object defined after
};

var person2 = {
name: "Jane",
lastName: "Doe",
age: 38,
gender: "female",
luckyNumbers: [2, 4, 6, 8],
significantOther: person
};

var family = {
lastName: "Doe",
members: [person, person2] //Array of objects, don't forget to add Jimmy
};


function addAllFamilyLuckyNumbers(anArray){
let sumOfAllLuckyNumbers = 0; //sumOfAllLuckyNumbers is a number, the sum of all lucky numbers.

//To-Do: loop and add; consider nested loops
//Hint: use the anArray variable to get all of the lucky numbers

return sumOfAllLuckyNumbers;
}

//Enter all your code here:


//Do not make changes below:
console.log(addAllFamilyLuckyNumbers(family.members));
52 changes: 52 additions & 0 deletions exercises/032-javascriptObjects/solution.hide.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
var person = {
name: "John", //String
lastName: "Doe",
age: 35, //Number
gender: "male",
luckyNumbers: [7, 11, 13, 17], //Array
significantOther: person2 //Object, yes, the same variable/object defined after
};

var person2 = {
name: "Jane",
lastName: "Doe",
age: 38,
gender: "female",
luckyNumbers: [2, 4, 6, 8],
significantOther: person
};

var person3 = {
name: 'Jimmy',
lastName: 'Doe',
age: 13,
gender: "male",
luckyNumbers: [1, 2, 3, 4],
significantOther: null
}

var family = {
lastName: "Doe",
members: [person, person2, person3] //Array of objects, don't forget to add Jimmy
};


function addAllFamilyLuckyNumbers(anArray) {
let sumOfAllLuckyNumbers = 0; //sumOfAllLuckyNumbers is a number, the sum of all lucky numbers.
for (let i = 0; i < anArray.length; i++) {
for (let x = 0; x < anArray[i].luckyNumbers.length; x++) {
sumOfAllLuckyNumbers += anArray[i].luckyNumbers[x];
}
}
//To-Do: loop and add; consider nested loops
//Hint: use the anArray variable to get all of the lucky numbers

return sumOfAllLuckyNumbers;
}

//Enter all your code here:
person.luckyNumbers[3] = 33;


//Do not make changes below:
console.log(addAllFamilyLuckyNumbers(family.members));
34 changes: 34 additions & 0 deletions exercises/032-javascriptObjects/tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const fs = require('fs');
const path = require('path');
const rewire = require('rewire');

jest.dontMock('fs');
//here we are going to store and accumulate (concatenate) all the console log's from the exercise
let _buffer = "";
let _log = console.log;

// lets override the console.log function to mock it,
// but we are also going to save what supposed to be the ouput of the console inside _buffer
global.console.log = console.log = jest.fn((text) => _buffer += text + "\n");

const file = rewire("./app.js");
const family = file.__get__("family");

describe('All the javascript should match', function () {
beforeEach(() => {
//here I import the HTML into the document
});
afterEach(() => { jest.resetModules(); });

it("John Doe's fourth lucky number should be 33" , function(){
expect(family.members[0].luckyNumbers[3]).toBe(33)
})

it('console.log() function should be called with 94 - sum of all family lucky numbers', function () {
const file = require("./app.js");
expect(_buffer).toBe("94\n");
//and I expect the console.log to be already called just one time.
expect(console.log.mock.calls.length).toBe(1);

});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `032` addFullNameProperty
# `033` addFullNameProperty

## 📝 Instrucciones:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `032` addFullNameProperty
# `033` addFullNameProperty

## 📝 Instructions:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `033` addObjectProperty
# `034` addObjectProperty

## 📝 Instrucciones:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `033` addObjectProperty
# `034` addObjectProperty

## 📝 Instructions:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `034` isPersonOldEnoughToDrive
# `035` isPersonOldEnoughToDrive

## 📝 Instrucciones:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `034` isPersonOldEnoughToDrive
# `035` isPersonOldEnoughToDrive

## 📝 Instructions:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `035` isPersonOldEnoughToVote
# `036` isPersonOldEnoughToVote

## 📝 Instrucciones:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `035` isPersonOldEnoughToVote
# `036` isPersonOldEnoughToVote

## 📝 Instructions:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `036` isPersonOldEnoughToDrink
# `037` isPersonOldEnoughToDrink

## 📝 Instrucciones:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `036` isPersonOldEnoughToDrink
# `037` isPersonOldEnoughToDrink

## 📝 Instructions:

Expand Down
Loading