Skip to content

Commit 830ce77

Browse files
authored
Merge pull request #316 from nahuelcoder/master
Array methods
2 parents 33f3ea4 + b070c86 commit 830ce77

File tree

25 files changed

+379
-379
lines changed

25 files changed

+379
-379
lines changed
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
function camelize(str) {
22
return str
3-
.split('-') // splits 'my-long-word' into array ['my', 'long', 'word']
3+
.split('-') // separa 'my-long-word' en el array ['my', 'long', 'word']
44
.map(
5-
// capitalizes first letters of all array items except the first one
6-
// converts ['my', 'long', 'word'] into ['my', 'Long', 'Word']
5+
// convierte en mayúscula todas las primeras letras de los elementos del array excepto por el primero
6+
// convierte ['my', 'long', 'word'] en ['my', 'Long', 'Word']
77
(word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
88
)
9-
.join(''); // joins ['my', 'Long', 'Word'] into 'myLongWord'
9+
.join(''); // une ['my', 'Long', 'Word'] en 'myLongWord'
1010
}

1-js/05-data-types/05-array-methods/1-camelcase/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@ importance: 5
22

33
---
44

5-
# Translate border-left-width to borderLeftWidth
5+
# Transforma border-left-width en borderLeftWidth
66

7-
Write the function `camelize(str)` that changes dash-separated words like "my-short-string" into camel-cased "myShortString".
7+
Escribe la función `camelize(str)` que convierta palabras separadas por guión como "mi-cadena-corta" en palabras con mayúscula "miCadenaCorta".
88

9-
That is: removes all dashes, each word after dash becomes uppercased.
9+
Esto sería: remover todos los guiones y que cada palabra después de un guión comience con mayúscula.
1010

11-
Examples:
11+
Ejemplos:
1212

1313
```js
1414
camelize("background-color") == 'backgroundColor';
1515
camelize("list-style-image") == 'listStyleImage';
1616
camelize("-webkit-transition") == 'WebkitTransition';
1717
```
1818

19-
P.S. Hint: use `split` to split the string into an array, transform it and `join` back.
19+
P.D. Pista: usa `split` para dividir el string en un array, transfórmalo y vuelve a unirlo (`join`).

1-js/05-data-types/05-array-methods/10-average-age/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 4
22

33
---
44

5-
# Get average age
5+
# Obtener edad promedio
66

7-
Write the function `getAverageAge(users)` that gets an array of objects with property `age` and returns the average age.
7+
Escribe la función `getAverageAge(users)` que obtenga un array de objetos con la propiedad `age` y devuelva el promedio de `age`.
88

9-
The formula for the average is `(age1 + age2 + ... + ageN) / N`.
9+
La fórmula de promedio es `(age1 + age2 + ... + ageN) / N`.
1010

11-
For instance:
11+
Por ejemplo:
1212

1313
```js no-beautify
1414
let john = { name: "John", age: 25 };

1-js/05-data-types/05-array-methods/11-array-unique/solution.md

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
Let's walk the array items:
2-
- For each item we'll check if the resulting array already has that item.
1+
Recorramos los elementos dentro del array:
2+
- Para cada elemento vamos a comprobar si el array resultante ya tiene ese elemento.
33
- If it is so, then ignore, otherwise add to results.
4+
- Si ya lo tiene ignora y continúa, si no, agrega el resultado.
45

56
```js run demo
67
function unique(arr) {
@@ -22,18 +23,18 @@ let strings = ["Hare", "Krishna", "Hare", "Krishna",
2223
alert( unique(strings) ); // Hare, Krishna, :-O
2324
```
2425

25-
The code works, but there's a potential performance problem in it.
26+
El código funciona pero tiene un problema potencial de desempeño.
2627

27-
The method `result.includes(str)` internally walks the array `result` and compares each element against `str` to find the match.
28+
El método `result.includes(str)` internamente recorre el array `result` y compara cada elemento con `str` para encontrar una coincidencia.
2829

29-
So if there are `100` elements in `result` and no one matches `str`, then it will walk the whole `result` and do exactly `100` comparisons. And if `result` is large, like `10000`, then there would be `10000` comparisons.
30+
Por lo tanto, si hay `100` elementos en `result` y ninguno coincide con `str`, entonces habrá recorrido todo el array `result` y ejecutado `100` comparaciones. Y si `result` es tan grande como `10000`, entonces habrá `10000` comparaciones.
3031

31-
That's not a problem by itself, because JavaScript engines are very fast, so walk `10000` array is a matter of microseconds.
32+
Esto no es un problema en sí mismo, porque los motores JavaScript son muy rápidos, por lo que recorrer `10000` elementos de un array solo le tomaría microsegundos.
3233

33-
But we do such test for each element of `arr`, in the `for` loop.
34+
Pero ejecutamos dicha comprobación para cada elemento de `arr` en el loop `for`.
3435

35-
So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 millions of comparisons. That's a lot.
36+
Entonces si `arr.length` es `10000` vamos a tener algo como `10000*10000` = 100 millones de comparaciones. Esto es realmente mucho.
3637

37-
So the solution is only good for small arrays.
38+
Por lo que la solución solo es buena para arrays pequeños.
3839

39-
Further in the chapter <info:map-set> we'll see how to optimize it.
40+
Más adelante en el capítulo <info:map-set> vamos a ver como optimizarlo.

1-js/05-data-types/05-array-methods/11-array-unique/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@ importance: 4
22

33
---
44

5-
# Filter unique array members
5+
# Filtrar elementos únicos de un array
66

7-
Let `arr` be an array.
7+
Partiendo del array `arr`.
88

9-
Create a function `unique(arr)` that should return an array with unique items of `arr`.
9+
Crea una función `unique(arr)` que devuelva un array con los elementos que se encuentran una sola vez dentro de `arr`.
1010

11-
For instance:
11+
Por ejemplo:
1212

1313
```js
1414
function unique(arr) {
15-
/* your code */
15+
/* tu código */
1616
}
1717

1818
let strings = ["Hare", "Krishna", "Hare", "Krishna",

1-js/05-data-types/05-array-methods/12-reduce-object/task.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 4
22

33
---
44

5-
# Create keyed object from array
5+
# Crea un objeto a partir de un array
66

7-
Let's say we received an array of users in the form `{id:..., name:..., age... }`.
7+
Supongamos que recibimos un array de usuarios con la forma `{id:..., name:..., age... }`.
88

9-
Create a function `groupById(arr)` that creates an object from it, with `id` as the key, and array items as values.
9+
Crea una función `groupById(arr)` que cree un objeto, con `id` como clave (key) y los elementos del array como valores.
1010

11-
For example:
11+
Por ejemplo:
1212

1313
```js
1414
let users = [
@@ -20,7 +20,7 @@ let users = [
2020
let usersById = groupById(users);
2121

2222
/*
23-
// after the call we should have:
23+
// después de llamar a la función deberíamos tener:
2424
2525
usersById = {
2626
john: {id: 'john', name: "John Smith", age: 20},
@@ -30,8 +30,8 @@ usersById = {
3030
*/
3131
```
3232

33-
Such function is really handy when working with server data.
33+
Dicha función es realmente útil cuando trabajamos con información del servidor.
3434

35-
In this task we assume that `id` is unique. There may be no two array items with the same `id`.
35+
Para esta actividad asumimos que cada `id` es único. No existen dos elementos del array con el mismo `id`.
3636

37-
Please use array `.reduce` method in the solution.
37+
Usa el método `array.reduce` en la solución.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

22
function filterRange(arr, a, b) {
3-
// added brackets around the expression for better readability
3+
// agregamos paréntesis en torno a la expresión para mayor legibilidad
44
return arr.filter(item => (a <= item && item <= b));
55
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
```js run demo
22
function filterRange(arr, a, b) {
3-
// added brackets around the expression for better readability
3+
// agregamos paréntesis en torno a la expresión para mayor legibilidad
44
return arr.filter(item => (a <= item && item <= b));
55
}
66

77
let arr = [5, 3, 8, 1];
88

99
let filtered = filterRange(arr, 1, 4);
1010

11-
alert( filtered ); // 3,1 (matching values)
11+
alert( filtered ); // 3,1 (valores dentro del rango)
1212

13-
alert( arr ); // 5,3,8,1 (not modified)
13+
alert( arr ); // 5,3,8,1 (array original no modificado)
1414
```

1-js/05-data-types/05-array-methods/2-filter-range/task.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,21 @@ importance: 4
22

33
---
44

5-
# Filter range
5+
# Filtrar un rango
66

7-
Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements between `a` and `b` in it and returns an array of them.
7+
Escribe una función `filterRange(arr, a, b)` que obtenga un array `arr`, busque los elementos entre `a` y `b` y devuelva un array con los resultados.
88

9-
The function should not modify the array. It should return the new array.
9+
La función no debe modificar el array. Debe devolver un nuevo array.
1010

11-
For instance:
11+
Por ejemplo:
1212

1313
```js
1414
let arr = [5, 3, 8, 1];
1515

1616
let filtered = filterRange(arr, 1, 4);
1717

18-
alert( filtered ); // 3,1 (matching values)
18+
alert( filtered ); // 3,1 (valores dentro del rango)
1919

20-
alert( arr ); // 5,3,8,1 (not modified)
20+
alert( arr ); // 5,3,8,1 (array original no modificado)
2121
```
2222

1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) {
44
for (let i = 0; i < arr.length; i++) {
55
let val = arr[i];
66

7-
// remove if outside of the interval
7+
// remueve aquellos elementos que se encuentran fuera del intervalo
88
if (val < a || val > b) {
99
arr.splice(i, 1);
1010
i--;

1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) {
44
for (let i = 0; i < arr.length; i++) {
55
let val = arr[i];
66

7-
// remove if outside of the interval
7+
// remueve aquellos elementos que se encuentran fuera del intervalo
88
if (val < a || val > b) {
99
arr.splice(i, 1);
1010
i--;
@@ -15,7 +15,7 @@ function filterRangeInPlace(arr, a, b) {
1515

1616
let arr = [5, 3, 8, 1];
1717

18-
filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4
18+
filterRangeInPlace(arr, 1, 4); // remueve los números excepto aquellos entre 1 y 4
1919

2020
alert( arr ); // [3, 1]
2121
```

1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@ importance: 4
22

33
---
44

5-
# Filter range "in place"
5+
# Filtrar rango "en el lugar"
66

7-
Write a function `filterRangeInPlace(arr, a, b)` that gets an array `arr` and removes from it all values except those that are between `a` and `b`. The test is: `a ≤ arr[i] ≤ b`.
7+
Escribe una función `filterRangeInPlace(arr, a, b)` que obtenga un array `arr` y remueva del mismo todos los valores excepto aquellos que se encuentran entre `a` y `b`. El test es: `a ≤ arr[i] ≤ b`.
88

9-
The function should only modify the array. It should not return anything.
9+
La función solo debe modificar el array. No debe devolver nada.
1010

11-
For instance:
11+
Por ejemplo:
1212
```js
1313
let arr = [5, 3, 8, 1];
1414

15-
filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4
15+
filterRangeInPlace(arr, 1, 4); // remueve los números excepto aquellos entre 1 y 4
1616

1717
alert( arr ); // [3, 1]
1818
```

1-js/05-data-types/05-array-methods/4-sort-back/task.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@ importance: 4
22

33
---
44

5-
# Sort in decreasing order
5+
# Ordenar en orden decreciente
66

77
```js
88
let arr = [5, 2, 1, -10, 8];
99

10-
// ... your code to sort it in decreasing order
10+
// ... tu código para ordenar en orden decreciente
1111

1212
alert( arr ); // 8, 5, 2, 1, -10
1313
```

1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
We can use `slice()` to make a copy and run the sort on it:
1+
Podemos usar `slice()` para crear una copia y realizar el ordenamiento en ella:
22

33
```js run
44
function copySorted(arr) {

1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@ importance: 5
22

33
---
44

5-
# Copy and sort array
5+
# Copia y ordena un array
66

7-
We have an array of strings `arr`. We'd like to have a sorted copy of it, but keep `arr` unmodified.
7+
Supongamos que tenemos un array `arr`. Nos gustaría tener una copia ordenada del mismo, pero mantener `arr` sin modificar.
88

9-
Create a function `copySorted(arr)` that returns such a copy.
9+
Crea una función `copySorted(arr)` que devuelva esa copia.
1010

1111
```js
1212
let arr = ["HTML", "JavaScript", "CSS"];
1313

1414
let sorted = copySorted(arr);
1515

1616
alert( sorted ); // CSS, HTML, JavaScript
17-
alert( arr ); // HTML, JavaScript, CSS (no changes)
17+
alert( arr ); // HTML, JavaScript, CSS (sin cambios)
1818
```

1-js/05-data-types/05-array-methods/6-array-get-names/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 5
22

33
---
44

5-
# Map to names
5+
# Mapa a nombres
66

7-
You have an array of `user` objects, each one has `user.name`. Write the code that converts it into an array of names.
7+
Tienes un array de objetos `user`, cada uno tiene `user.name`. Escribe el código que lo convierta en un array de nombres.
88

9-
For instance:
9+
Por ejemplo:
1010

1111
```js no-beautify
1212
let john = { name: "John", age: 25 };
@@ -15,7 +15,7 @@ let mary = { name: "Mary", age: 28 };
1515

1616
let users = [ john, pete, mary ];
1717

18-
let names = /* ... your code */
18+
let names = /* ... tu código */
1919

2020
alert( names ); // John, Pete, Mary
2121
```
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11

2-
- Please note how methods are stored. They are simply added to `this.methods` property.
3-
- All tests and numeric conversions are done in the `calculate` method. In future it may be extended to support more complex expressions.
2+
- Por favor ten en cuenta cómo son almacenados los métodos. Simplemente son agregados a la propiedad `this.methods`.
3+
- Todos los test y conversiones son hechas con el método `calculate`. En el futuro puede ser extendido para soportar expresiones más complejas.

1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,24 @@ importance: 5
22

33
---
44

5-
# Create an extendable calculator
5+
# Crea una calculadora extensible
66

7-
Create a constructor function `Calculator` that creates "extendable" calculator objects.
7+
Crea una función `Calculator` que cree objetos calculadores "extensibles".
88

9-
The task consists of two parts.
9+
La actividad consiste de dos partes.
1010

11-
1. First, implement the method `calculate(str)` that takes a string like `"1 + 2"` in the format "NUMBER operator NUMBER" (space-delimited) and returns the result. Should understand plus `+` and minus `-`.
11+
1. Primero, implementar el método `calculate(str)` que toma un string como `"1 + 2"` en el formato "NUMERO operador NUMERO" (delimitado por espacios) y devuelve el resultado. Debe entender más `+` y menos `-`.
1212

13-
Usage example:
13+
Ejemplo de uso:
1414

1515
```js
1616
let calc = new Calculator;
1717

1818
alert( calc.calculate("3 + 7") ); // 10
1919
```
20-
2. Then add the method `addMethod(name, func)` that teaches the calculator a new operation. It takes the operator `name` and the two-argument function `func(a,b)` that implements it.
20+
2. Luego agrega el método `addMethod(name, func)` que enseñe a la calculadora una nueva operación. Toma el operador `name` y la función con dos argumentos `func(a,b)` que lo implementa.
2121

22-
For instance, let's add the multiplication `*`, division `/` and power `**`:
22+
Por ejemplo, vamos a agregar la multiplicación `*`, division `/` y potencia `**`:
2323

2424
```js
2525
let powerCalc = new Calculator;
@@ -31,6 +31,6 @@ The task consists of two parts.
3131
alert( result ); // 8
3232
```
3333

34-
- No parentheses or complex expressions in this task.
35-
- The numbers and the operator are delimited with exactly one space.
36-
- There may be error handling if you'd like to add it.
34+
- Sin paréntesis ni expresiones complejas.
35+
- Los números y el operador deben estar delimitados por exactamente un espacio.
36+
- Puede haber manejo de errores si quisieras agregarlo.

0 commit comments

Comments
 (0)