From 042d43fcb0a81e3ad3b5d048248ff50a541ee2ce Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Sun, 19 Jul 2020 19:51:02 -0300 Subject: [PATCH 01/28] Arrays --- .../04-array/1-item-value/solution.md | 4 +- .../04-array/1-item-value/task.md | 10 +- .../04-array/10-maximal-subarray/solution.md | 44 +-- .../04-array/10-maximal-subarray/task.md | 18 +- .../04-array/2-create-array/task.md | 16 +- .../04-array/3-call-array-this/solution.md | 6 +- .../04-array/3-call-array-this/task.md | 4 +- .../04-array/5-array-input-sum/solution.md | 6 +- .../04-array/5-array-input-sum/task.md | 12 +- 1-js/05-data-types/04-array/article.md | 280 +++++++++--------- 10 files changed, 200 insertions(+), 200 deletions(-) diff --git a/1-js/05-data-types/04-array/1-item-value/solution.md b/1-js/05-data-types/04-array/1-item-value/solution.md index e631f1c70..6f93b6775 100644 --- a/1-js/05-data-types/04-array/1-item-value/solution.md +++ b/1-js/05-data-types/04-array/1-item-value/solution.md @@ -1,4 +1,4 @@ -The result is `4`: +El resultado es `4`: ```js run @@ -13,5 +13,5 @@ alert( fruits.length ); // 4 */!* ``` -That's because arrays are objects. So both `shoppingCart` and `fruits` are the references to the same array. +Esto es porque los arrays son objetos. Entonces ambos, `shoppingCart` y `fruits` son referencias al mismo array. diff --git a/1-js/05-data-types/04-array/1-item-value/task.md b/1-js/05-data-types/04-array/1-item-value/task.md index 4fcf384fb..86cf589eb 100644 --- a/1-js/05-data-types/04-array/1-item-value/task.md +++ b/1-js/05-data-types/04-array/1-item-value/task.md @@ -2,18 +2,18 @@ importance: 3 --- -# Is array copied? +# ¿El array es copiado? -What is this code going to show? +¿Qué va a mostrar este código? ```js let fruits = ["Apples", "Pear", "Orange"]; -// push a new value into the "copy" +// introduce un valor nuevo dentro de una copia let shoppingCart = fruits; shoppingCart.push("Banana"); -// what's in fruits? -alert( fruits.length ); // ? +// ¿Qué hay en "fruits"? +alert( fruits.length ); // ¿? ``` diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md index daadf494b..ed556e738 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md @@ -1,43 +1,43 @@ -# Slow solution +# Solución lenta -We can calculate all possible subsums. +Podemos calcular todas las subsumas. -The simplest way is to take every element and calculate sums of all subarrays starting from it. +La más simple forma es tomar cada elemento y calcular las sumas de todos los subarrays que comienzan con él. -For instance, for `[-1, 2, 3, -9, 11]`: +Por ejemplo, para `[-1, 2, 3, -9, 11]`: ```js no-beautify -// Starting from -1: +// Comenzando desde -1: -1 -1 + 2 -1 + 2 + 3 -1 + 2 + 3 + (-9) -1 + 2 + 3 + (-9) + 11 -// Starting from 2: +// Comenzando desde 2: 2 2 + 3 2 + 3 + (-9) 2 + 3 + (-9) + 11 -// Starting from 3: +// Comenzando desde 3: 3 3 + (-9) 3 + (-9) + 11 -// Starting from -9 +// Comenzando desde -9 -9 -9 + 11 -// Starting from 11 +// Comenzando desde 11 11 ``` -The code is actually a nested loop: the external loop over array elements, and the internal counts subsums starting with the current element. +El código es un bucle anidado. El bucle externo itera sobre los elementos del array, y el interno cuenta subsumas comenzando con cada uno de ellos. ```js run function getMaxSubSum(arr) { - let maxSum = 0; // if we take no elements, zero will be returned + let maxSum = 0; // si no obtenemos elementos, devolverá cero for (let i = 0; i < arr.length; i++) { let sumFixedStart = 0; @@ -57,25 +57,25 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6 alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100 ``` -The solution has a time complexety of [O(n2)](https://en.wikipedia.org/wiki/Big_O_notation). In other words, if we increase the array size 2 times, the algorithm will work 4 times longer. +La solución tiene una complejidad 2 en notación Landau (coste respecto al tiempo) [O(n2)](https://es.wikipedia.org/wiki/Notaci%C3%B3n_de_Landau). Es decir, si multiplicamos el tamaño del array por 2, el tiempo del algoritmo se multiplicará por 4. -For big arrays (1000, 10000 or more items) such algorithms can lead to a serious sluggishness. +Para arrays muy grandes (1000, 10000 o más items) tales algoritmos llevarán a una severa lentitud. -# Fast solution +# Solución rápida -Let's walk the array and keep the current partial sum of elements in the variable `s`. If `s` becomes negative at some point, then assign `s=0`. The maximum of all such `s` will be the answer. +Recorramos el array y registremos la suma parcial corriente de los elementos en la variable `s`. Si `s` se vuelve cero en algún punto, le asignamos `s=0`. El máximo entre todas las sumas parciales `s` será la respuesta. -If the description is too vague, please see the code, it's short enough: +Si la descripción te resulta demasiado vaga, por favor mira el código. Es bastante corto: ```js run demo function getMaxSubSum(arr) { let maxSum = 0; let partialSum = 0; - for (let item of arr) { // for each item of arr - partialSum += item; // add it to partialSum - maxSum = Math.max(maxSum, partialSum); // remember the maximum - if (partialSum < 0) partialSum = 0; // zero if negative + for (let item of arr) { // para cada item de arr + partialSum += item; // se lo suma a partialSum + maxSum = Math.max(maxSum, partialSum); // registra el máximo + if (partialSum < 0) partialSum = 0; // cero si se vuelve negativo } return maxSum; @@ -89,6 +89,6 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6 alert( getMaxSubSum([-1, -2, -3]) ); // 0 ``` -The algorithm requires exactly 1 array pass, so the time complexity is O(n). +El algoritmo requiere exactamente una pasada, entonces la complejidad es O(n). -You can find more detail information about the algorithm here: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). If it's still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that's better than any words. +Puedes encontrar información detallada acerca del algoritmo: [Subvector de suma máxima](https://es.wikibooks.org/wiki/Algoritmia/Divide_y_vencer%C3%A1s#Subvector_de_suma_m%C3%A1xima). Si aún no es obvio cómo funciona, traza el algoritmo en los ejemplos de arriba y observa cómo trabaja, es mejor que cualquier explicación. diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/task.md b/1-js/05-data-types/04-array/10-maximal-subarray/task.md index f1a1d9f95..ddba982a0 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/task.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/task.md @@ -2,29 +2,29 @@ importance: 2 --- -# A maximal subarray +# Subarray máximo -The input is an array of numbers, e.g. `arr = [1, -2, 3, 4, -9, 6]`. +La entrada es un array de números, por ejemplo `arr = [1, -2, 3, 4, -9, 6]`. -The task is: find the contiguous subarray of `arr` with the maximal sum of items. +La tarea es: encuentra el subarray contiguo de items de `arr` con la suma máxima. -Write the function `getMaxSubSum(arr)` that will return that sum. +Escribe la función `getMaxSubSum(arr)` que devuelva tal sumo. -For instance: +Por ejemplo: ```js -getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (the sum of highlighted items) +getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (la suma de items resaltados) getMaxSubSum([*!*2, -1, 2, 3*/!*, -9]) == 6 getMaxSubSum([-1, 2, 3, -9, *!*11*/!*]) == 11 getMaxSubSum([-2, -1, *!*1, 2*/!*]) == 3 getMaxSubSum([*!*100*/!*, -9, 2, -3, 5]) == 100 -getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (take all) +getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (toma todo) ``` -If all items are negative, it means that we take none (the subarray is empty), so the sum is zero: +Si todos los elementos son negativos, significa que que no tomamos ninguno (el subarray está vacío), entonces la suma es cero: ```js getMaxSubSum([-1, -2, -3]) = 0 ``` -Please try to think of a fast solution: [O(n2)](https://en.wikipedia.org/wiki/Big_O_notation) or even O(n) if you can. +Trata de pensar un solución rápida: [O(n2)](https://es.wikipedia.org/wiki/Notaci%C3%B3n_de_Landau) o incluso O(n) si puedes. diff --git a/1-js/05-data-types/04-array/2-create-array/task.md b/1-js/05-data-types/04-array/2-create-array/task.md index 16d14071f..c3989ba59 100644 --- a/1-js/05-data-types/04-array/2-create-array/task.md +++ b/1-js/05-data-types/04-array/2-create-array/task.md @@ -2,17 +2,17 @@ importance: 5 --- -# Array operations. +# Operaciones en arrays. -Let's try 5 array operations. +Tratemos 5 operaciones de array. -1. Create an array `styles` with items "Jazz" and "Blues". -2. Append "Rock-n-Roll" to the end. -3. Replace the value in the middle by "Classics". Your code for finding the middle value should work for any arrays with odd length. -4. Strip off the first value of the array and show it. -5. Prepend `Rap` and `Reggae` to the array. +1. Crear un array `styles` con los items "Jazz" y "Blues". +2. Agregar "Rock-n-Roll" al final. +3. Reemplazar el valor en el medio por "Classics". Tu código para encontrar el valor medio debe funcionar con cualquier array de largo impar. +4. Quitar el primer valor del array y mostrarlo. +5. Anteponer `Rap` y `Reggae` al array. -The array in the process: +El array durante el proceso: ```js no-beautify Jazz, Blues diff --git a/1-js/05-data-types/04-array/3-call-array-this/solution.md b/1-js/05-data-types/04-array/3-call-array-this/solution.md index 3cb0317cf..e4760ae01 100644 --- a/1-js/05-data-types/04-array/3-call-array-this/solution.md +++ b/1-js/05-data-types/04-array/3-call-array-this/solution.md @@ -1,6 +1,6 @@ -The call `arr[2]()` is syntactically the good old `obj[method]()`, in the role of `obj` we have `arr`, and in the role of `method` we have `2`. +El llamado a `arr[2]()` es sintácticamente el buen y viejo `obj[method]()`, el el rol de `obj` tenemos `arr`, y en el rol de `method` tenemos `2`. -So we have a call of the function `arr[2]` as an object method. Naturally, it receives `this` referencing the object `arr` and outputs the array: +Entonces tenemos una llamada a función `arr[2]` como un método de objeto. Naturalmente, recibe `this` referenciando el objeto `arr` y su salida es el array: ```js run let arr = ["a", "b"]; @@ -12,4 +12,4 @@ arr.push(function() { arr[2](); // a,b,function(){...} ``` -The array has 3 values: initially it had two, plus the function. +El array tiene 3 valores: Iniciamente tenía 2 y se agregó la función. diff --git a/1-js/05-data-types/04-array/3-call-array-this/task.md b/1-js/05-data-types/04-array/3-call-array-this/task.md index 340c5feef..f97de8eb9 100644 --- a/1-js/05-data-types/04-array/3-call-array-this/task.md +++ b/1-js/05-data-types/04-array/3-call-array-this/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Calling in an array context +# LLamados en un contexto de array -What is the result? Why? +¿Cuál es el resultado?¿Por qué? ```js let arr = ["a", "b"]; diff --git a/1-js/05-data-types/04-array/5-array-input-sum/solution.md b/1-js/05-data-types/04-array/5-array-input-sum/solution.md index 75bd683b5..9b9a4d9e0 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/solution.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/solution.md @@ -1,4 +1,4 @@ -Please note the subtle, but important detail of the solution. We don't convert `value` to number instantly after `prompt`, because after `value = +value` we would not be able to tell an empty string (stop sign) from the zero (valid number). We do it later instead. +Toma nota del sutil pero importante detalle de la solución. No convertimos `value` a número instantáneamente después de `prompt`, porque después de `value = +value` no seríamos capaces de diferenciar una cadena vacía (señal de detención) de un cero (un número válido). Lo hacemos más adelante. ```js run demo @@ -8,9 +8,9 @@ function sumInput() { while (true) { - let value = prompt("A number please?", 0); + let value = prompt("¿Un número por favor?", 0); - // should we cancel? + // ¿Debemos cancelar? if (value === "" || value === null || !isFinite(value)) break; numbers.push(+value); diff --git a/1-js/05-data-types/04-array/5-array-input-sum/task.md b/1-js/05-data-types/04-array/5-array-input-sum/task.md index 4af8e7c95..f95476111 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/task.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/task.md @@ -2,14 +2,14 @@ importance: 4 --- -# Sum input numbers +# Suma de números ingresados -Write the function `sumInput()` that: +Escribe una función `sumInput()` que: -- Asks the user for values using `prompt` and stores the values in the array. -- Finishes asking when the user enters a non-numeric value, an empty string, or presses "Cancel". -- Calculates and returns the sum of array items. +- Pida al usuario valores usando `prompt` y los almacene en el array. +- Termine de pedirlos cuando el usuario entre un valor no numérico, una cadena vacía, o presione "Escape". +- Calcule y devuelva la suma de los items del array. -P.S. A zero `0` is a valid number, please don't stop the input on zero. +P.D. Un cero `0` es un número válido, por favor no detenga los ingresos con el cero. [demo] diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 33498f40a..d046c8cc4 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -1,31 +1,31 @@ # Arrays -Objects allow you to store keyed collections of values. That's fine. +Los objetos te permiten almacenar colecciones de datos a través de nombres. Eso está bien. -But quite often we find that we need an *ordered collection*, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc. +Pero a menudo necesitamos una *colección ordenada*, donde tenemos un 1ro, un 2do, un 3er elemento y así sucesivamente. Por ejemplo, necesitamos almacenar una lista de algo: usuarios, bienes, elementos HTML, etc. -It is not convenient to use an object here, because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use. +No es conveniente usar objetos aquí, porque no proveen métodos para manejar el orden de los elementos. No podemos insertar una nueva propiedad “entre” los exitentes. Los objetos no están hechos para eso. -There exists a special data structure named `Array`, to store ordered collections. +Existe una estructura llamada `Array` (llamada en español arreglo o matriz/vector) para almacenar colecciones ordenadas. -## Declaration +## Declaración -There are two syntaxes for creating an empty array: +Hay dos sintaxis para crear un array vacío: ```js let arr = new Array(); let arr = []; ``` -Almost all the time, the second syntax is used. We can supply initial elements in the brackets: +Casi siempre se usa la segunda. Podemos suministrar elementos iniciales entre los corchetes: ```js let fruits = ["Apple", "Orange", "Plum"]; ``` -Array elements are numbered, starting with zero. +Los elementoss del array están numerados, comenzando desde cero. -We can get an element by its number in square brackets: +Podemos obtener un elemento por su número entre corchetes: ```js run let fruits = ["Apple", "Orange", "Plum"]; @@ -35,19 +35,19 @@ alert( fruits[1] ); // Orange alert( fruits[2] ); // Plum ``` -We can replace an element: +Podemos reemplazar un elemento: ```js -fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"] +fruits[2] = 'Pear'; // ahora ["Apple", "Orange", "Pear"] ``` -...Or add a new one to the array: +...o agregar uno nuevo al array: ```js -fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"] +fruits[3] = 'Lemon'; // ahora ["Apple", "Orange", "Pear", "Lemon"] ``` -The total count of the elements in the array is its `length`: +La cuenta total de elementos en el array es su largo `length`: ```js run let fruits = ["Apple", "Orange", "Plum"]; @@ -55,7 +55,7 @@ let fruits = ["Apple", "Orange", "Plum"]; alert( fruits.length ); // 3 ``` -We can also use `alert` to show the whole array. +También podemos usar `alert` para mostrar el array completo. ```js run let fruits = ["Apple", "Orange", "Plum"]; @@ -63,24 +63,24 @@ let fruits = ["Apple", "Orange", "Plum"]; alert( fruits ); // Apple,Orange,Plum ``` -An array can store elements of any type. +Un array puede almacenar elementos de cualquier tipo. -For instance: +Por ejemplo: ```js run no-beautify -// mix of values +// mezcla de valores let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ]; -// get the object at index 1 and then show its name +// obtener el objeto del índice 1 y mostrar su nombre alert( arr[1].name ); // John -// get the function at index 3 and run it +// obtener la función del índice 3 y ejecutarla arr[3](); // hello ``` -````smart header="Trailing comma" -An array, just like an object, may end with a comma: +````smart header="Coma residual" +Un array, al igual que un objeto, puede tener una coma final: ```js let fruits = [ "Apple", @@ -89,57 +89,57 @@ let fruits = [ ]; ``` -The "trailing comma" style makes it easier to insert/remove items, because all lines become alike. +La "coma final" hace más simple insertar y remover items, porque todas la líneas se vuelven similares. ```` -## Methods pop/push, shift/unshift +## Métodos pop/push, shift/unshift -A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is one of the most common uses of an array. In computer science, this means an ordered collection of elements which supports two operations: +Una [cola](https://es.wikipedia.org/wiki/Cola_(inform%C3%A1tica)) es uno de los usos más comunes de un array. En ciencias de la computación, significa una colección ordenada de elementos que soportan dos operaciones: -- `push` appends an element to the end. -- `shift` get an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st. +- `push` inserta un elemento al final. +- `shift` obtiene el elemento del principio, avanzando la cola, y así el segundo elemento se vuelve primero. ![](queue.svg) -Arrays support both operations. +Los arrays soportan ambas operaciones. -In practice we need it very often. For example, a queue of messages that need to be shown on-screen. +En la práctica los necesitamos muy a menudo. Por ejemplo, una cola de mensajes que necesitamos mostrar en pantalla. -There's another use case for arrays -- the data structure named [stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)). +Hay otro caso de uso para los arrays -- la estructura de datos llamada [pila](https://es.wikipedia.org/wiki/Pila_(inform%C3%A1tica)). -It supports two operations: +Ella soporta dos operaciones: -- `push` adds an element to the end. -- `pop` takes an element from the end. +- `push` agrega un elemento al final. +- `pop` toma un elemento desde el final. -So new elements are added or taken always from the "end". +Entonces los elementos nuevos son agregados o tomados siempre desde el "final". -A stack is usually illustrated as a pack of cards: new cards are added to the top or taken from the top: +Una pila es usualmente mostrada como un mazo de cartas, donde las nuevas cartas son agregadas al tope o tomadas desde el tope: ![](stack.svg) -For stacks, the latest pushed item is received first, that's also called LIFO (Last-In-First-Out) principle. For queues, we have FIFO (First-In-First-Out). +Para las pilas, la última introducida es la primera en ser recibida, en inglés esto es llamado principio LIFO (Last-In-First-Out, última en entrar primera en salir). Para las colas, tenemos FIFO (First-In-First-Out primera en entrar, primera en salir). -Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements both to/from the beginning or the end. +Los arrays en JavaScript pueden trabajar como colas o pilas. Ellos permiten agregar o quitar elementos a y desde el principio o a y desde el final. -In computer science the data structure that allows this, is called [deque](https://en.wikipedia.org/wiki/Double-ended_queue). +En ciencias de la computación la estructura de datos que permite esto se denomina cola de doble extremo o [bicola](https://es.wikipedia.org/wiki/Bicola). -**Methods that work with the end of the array:** +**Métodos que trabajan sobre el final del array:** `pop` -: Extracts the last element of the array and returns it: +: Extrae el último elemento del array y lo devuelve: ```js run let fruits = ["Apple", "Orange", "Pear"]; - alert( fruits.pop() ); // remove "Pear" and alert it + alert( fruits.pop() ); // quita "Pear" y lo muestra alert( fruits ); // Apple, Orange ``` `push` -: Append the element to the end of the array: +: Agrega el elemento al final del array: ```js run let fruits = ["Apple", "Orange"]; @@ -149,23 +149,23 @@ In computer science the data structure that allows this, is called [deque](https alert( fruits ); // Apple, Orange, Pear ``` - The call `fruits.push(...)` is equal to `fruits[fruits.length] = ...`. + El llamado a `fruits.push(...)` es igual a `fruits[fruits.length] = ...`. -**Methods that work with the beginning of the array:** +**Métodos que trabajan con el principio del array:** `shift` -: Extracts the first element of the array and returns it: +: Extrae el primer elemento del array y lo devuelve: ```js run let fruits = ["Apple", "Orange", "Pear"]; - alert( fruits.shift() ); // remove Apple and alert it + alert( fruits.shift() ); // quita Apple y lo muestra alert( fruits ); // Orange, Pear ``` `unshift` -: Add the element to the beginning of the array: +: Agrega el elemento al principio del array: ```js run let fruits = ["Orange", "Pear"]; @@ -175,7 +175,7 @@ In computer science the data structure that allows this, is called [deque](https alert( fruits ); // Apple, Orange, Pear ``` -Methods `push` and `unshift` can add multiple elements at once: +Los métodos `push` y `unshift` pueden agregar múltiples elementos de una vez: ```js run let fruits = ["Apple"]; @@ -187,97 +187,97 @@ fruits.unshift("Pineapple", "Lemon"); alert( fruits ); ``` -## Internals +## Internamente -An array is a special kind of object. The square brackets used to access a property `arr[0]` actually come from the object syntax. That's essentially the same as `obj[key]`, where `arr` is the object, while numbers are used as keys. +Un array es una clase especial de objeto. Los corchetes usados para acceder a una propiedad `arr[0]` vienen de la sintaxi de objeto. Son esencialmente lo mismo que `obj[key]`, donde `arr` es el objeto mientras los números son usados como claves. -They extend objects providing special methods to work with ordered collections of data and also the `length` property. But at the core it's still an object. +Ellos extienden los objetos proveyendo métodos especiales para trabajar con colecciones ordenadas de datos y también la propiedad `length`. Pero el corazón es aún un objeto. -Remember, there are only 7 basic types in JavaScript. Array is an object and thus behaves like an object. +Recuerda, hay solo 7 tipos basicos en JavaScript. Array es un objeto y se comporta como un objeto.. -For instance, it is copied by reference: +Por ejemplo, es copiado por referencia: ```js run let fruits = ["Banana"] -let arr = fruits; // copy by reference (two variables reference the same array) +let arr = fruits; // copiado por referencia (dos variables referencian al mismo array) alert( arr === fruits ); // true -arr.push("Pear"); // modify the array by reference +arr.push("Pear"); // modifica el array por referencia -alert( fruits ); // Banana, Pear - 2 items now +alert( fruits ); // Banana, Pear - ahora con 2 items ``` -...But what makes arrays really special is their internal representation. The engine tries to store its elements in the contiguous memory area, one after another, just as depicted on the illustrations in this chapter, and there are other optimizations as well, to make arrays work really fast. +...Pero lo que hace a los array realmente especiales es su representación interna. El motor trata de almacenarlos en áreas de memoria contigua, uno tras otro, justo como muestra la ilustración en este capítulo. Hay otras optimizaciones también para hacer que los arrays trabajen verdaderamente rápido. -But they all break if we quit working with an array as with an "ordered collection" and start working with it as if it were a regular object. +Pero todo esto se puede malograr si dejamos de trabajarlos como arrays de colecciones ordenadas y comenzamos a usarlos como si fueran objetos comunes. -For instance, technically we can do this: +Por ejemplo, técnicamente podemos hacer esto: ```js -let fruits = []; // make an array +let fruits = []; // crea un array -fruits[99999] = 5; // assign a property with the index far greater than its length +fruits[99999] = 5; // asigna una propiedad con un índice mucho mayor que su largo -fruits.age = 25; // create a property with an arbitrary name +fruits.age = 25; // crea una propiedad con un nombre arbitrario ``` -That's possible, because arrays are objects at their base. We can add any properties to them. +Esto es posible porque los arrays son objetos en su base. Podemos agregar cualquier propiedad en ellos. -But the engine will see that we're working with the array as with a regular object. Array-specific optimizations are not suited for such cases and will be turned off, their benefits disappear. +Pero el motor verá que estamos tratándolo como un objeto común. Las optimizaciones específicas no son aptas para tales casos y serán desechadas, y sus beneficios desaparecerán. -The ways to misuse an array: +Las formas de malograr un array: -- Add a non-numeric property like `arr.test = 5`. -- Make holes, like: add `arr[0]` and then `arr[1000]` (and nothing between them). -- Fill the array in the reverse order, like `arr[1000]`, `arr[999]` and so on. +- Agregar una propiedad no numérica como `arr.test = 5`. +- Generar agujeros como: agregar `arr[0]` y luego `arr[1000]` (y nada entre ellos). +- Llenar el array en orden inverso, como `arr[1000]`, `arr[999]` y así. -Please think of arrays as special structures to work with the *ordered data*. They provide special methods for that. Arrays are carefully tuned inside JavaScript engines to work with contiguous ordered data, please use them this way. And if you need arbitrary keys, chances are high that you actually require a regular object `{}`. +Piensa en los arrays como estructuras especiales para trabajar con *datos ordenados*. Ellos proveen métodos especiales para ello. Los arrays están cuidadosamente afinados dentro de los motores JavaScript para funcionar con datos ordenados contiguos, por favor úsalos de esa manera. Y si necesitas claves arbitrarias, hay altas chances de que en realidad necesites objetos comunes `{}`. ## Performance -Methods `push/pop` run fast, while `shift/unshift` are slow. +Los métodos `push/pop` son rápidos, mientras que `shift/unshift` son lentos. ![](array-speed.svg) -Why is it faster to work with the end of an array than with its beginning? Let's see what happens during the execution: +¿Por qué es más rapido trabajar con el final del array que con el principio? Veamos qué pasa durante la ejecución: ```js -fruits.shift(); // take 1 element from the start +fruits.shift(); // toma 1 elemento del principio ``` -It's not enough to take and remove the element with the number `0`. Other elements need to be renumbered as well. +No es suficiente tomar y eliminar el elemento con el índice `0`. Los demás elementos necesitan ser renumerados también. -The `shift` operation must do 3 things: +La operación `shift` debe hacer 3 cosas: -1. Remove the element with the index `0`. -2. Move all elements to the left, renumber them from the index `1` to `0`, from `2` to `1` and so on. -3. Update the `length` property. +1. Remover el elemento con índice `0`. +2. Mover todos lo elementos hacia la izquierda y renumerarlos: desde el índice `1` a `0`, de `2` a `1` y así sucesivamente. +3. Actualizar el largo: la propiedad `length`. ![](array-shift.svg) -**The more elements in the array, the more time to move them, more in-memory operations.** +**Cuanto más elementos haya en el array, más tiempo tomará moverlos, más operaciones en memoria.** -The similar thing happens with `unshift`: to add an element to the beginning of the array, we need first to move existing elements to the right, increasing their indexes. +Algo similar ocurre con `unshift`: para agregar un elemento al principio del array, necesitamos primero mover todos los elementos hacia la derecha, incrementando sus índices. -And what's with `push/pop`? They do not need to move anything. To extract an element from the end, the `pop` method cleans the index and shortens `length`. +¿Y qué pasa con `push/pop`? Ellos no necesitan mover nada. Para extraer un elemento del final, el método `pop` limpia el índice y acorta `length`. -The actions for the `pop` operation: +Las acciones para la operación `pop`: ```js -fruits.pop(); // take 1 element from the end +fruits.pop(); // toma 1 elemento del final ``` ![](array-pop.svg) -**The `pop` method does not need to move anything, because other elements keep their indexes. That's why it's blazingly fast.** +**El método `pop` no necesita mover nada, porque los demás elementos mantienen sus índices. Es por ello que es muy rápido.** -The similar thing with the `push` method. +Algo similar ocurre con el método `push`. -## Loops +## Bucles -One of the oldest ways to cycle array items is the `for` loop over indexes: +Una de las formas más viejas de iterar los items de un array es el bucle `for` sobre sus índices: ```js run let arr = ["Apple", "Orange", "Pear"]; @@ -289,20 +289,20 @@ for (let i = 0; i < arr.length; i++) { } ``` -But for arrays there is another form of loop, `for..of`: +Pero para los arrays también hay otra forma de bucle,`for..of`: ```js run let fruits = ["Apple", "Orange", "Plum"]; -// iterates over array elements +// itera sobre los elementos del array for (let fruit of fruits) { alert( fruit ); } ``` -The `for..of` doesn't give access to the number of the current element, just its value, but in most cases that's enough. And it's shorter. +`for..of` no da acceso al número del elemento en curso, solamente a su valor, pero en la mayoría de los casos eso es suficiente. Y es más corto. -Technically, because arrays are objects, it is also possible to use `for..in`: +Técnicamente, y porque los arrays son objetos, es también posible usar `for..in`: ```js run let arr = ["Apple", "Orange", "Pear"]; @@ -314,22 +314,22 @@ for (let key in arr) { } ``` -But that's actually a bad idea. There are potential problems with it: +Pero es una mala idea. Existen problemas potenciales con esto: -1. The loop `for..in` iterates over *all properties*, not only the numeric ones. +1. El bucle `for..in` itera sobre *todas las propiedades*, no solo las numéricas. - There are so-called "array-like" objects in the browser and in other environments, that *look like arrays*. That is, they have `length` and indexes properties, but they may also have other non-numeric properties and methods, which we usually don't need. The `for..in` loop will list them though. So if we need to work with array-like objects, then these "extra" properties can become a problem. + Existen objetos "simil-array" en el navegador y otros ambientes que *parecen arrays*. Esto es, tienen `length` y propiedades indexadas, pero pueden también tener propiedades no numéricas y métodos que usualmente no necesitemos. Y el bucle `for..in` los listará. Entonces si necesitamos trabajar con objetos simil-array, estas propiedades "extras" pueden volverse un problema. -2. The `for..in` loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it's still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference. +2. El bucle `for..in` está optimizado para objetos genéricos, no arrays, y es de 10 a 100 veces más lento. Por supuesto es aún muy rápido. La aceleración puede ser solamente cuestión de cuellos de botella. Pero aún necesitamos percatarnos de la diferencia. -Generally, we shouldn't use `for..in` for arrays. +En general, no deberíamos usar `for..in` en arrays. -## A word about "length" +## Acerca de "length" -The `length` property automatically updates when we modify the array. To be precise, it is actually not the count of values in the array, but the greatest numeric index plus one. +La propiedad `length` automáticamente se actualiza cuando se modifica el array. Para ser precisos, no es la cuenta de valores del array sino el mayor índice más uno. -For instance, a single element with a large index gives a big length: +Por ejemplo, un elemento simple con un índice grande da un largo grande: ```js run let fruits = []; @@ -338,54 +338,54 @@ fruits[123] = "Apple"; alert( fruits.length ); // 124 ``` -Note that we usually don't use arrays like that. +Nota que usualmente no usamos arrays de este modo. -Another interesting thing about the `length` property is that it's writable. +Otra cosa interesante acerca de la propiedad `length` es que se puede sobrescribir. -If we increase it manually, nothing interesting happens. But if we decrease it, the array is truncated. The process is irreversible, here's the example: +Si la incrementamos manualmente, nada interesante ocurre. Pero si la decrementamos, el array es truncado. El proceso es irreversible, aquí el ejemplo: ```js run let arr = [1, 2, 3, 4, 5]; -arr.length = 2; // truncate to 2 elements +arr.length = 2; // truncamos a 2 elementos alert( arr ); // [1, 2] -arr.length = 5; // return length back -alert( arr[3] ); // undefined: the values do not return +arr.length = 5; // reponemos el largo length +alert( arr[3] ); // undefined: el valor no se recupera ``` -So, the simplest way to clear the array is: `arr.length = 0;`. +Entonces la forma más simple de limpiar un array es: `arr.length = 0;`. ## new Array() [#new-array] -There is one more syntax to create an array: +Hay una sintaxis más para crear un array: ```js let arr = *!*new Array*/!*("Apple", "Pear", "etc"); ``` -It's rarely used, because square brackets `[]` are shorter. Also there's a tricky feature with it. +Es raramente usada porque con corchetes `[]` es más corto. También hay una característica peculiar con ella. -If `new Array` is called with a single argument which is a number, then it creates an array *without items, but with the given length*. +Si `new Array` es llamado con un único argumento numérico, se crea un array *sin items, pero con el largo "length" dado*. -Let's see how one can shoot themself in the foot: +Veamos cómo uno puede dispararse en el pie: ```js run -let arr = new Array(2); // will it create an array of [2] ? +let arr = new Array(2); // ¿Creará un array de [2]? -alert( arr[0] ); // undefined! no elements. +alert( arr[0] ); // undefined! sin elementos. -alert( arr.length ); // length 2 +alert( arr.length ); // largo 2 ``` -In the code above, `new Array(number)` has all elements `undefined`. +En el código anterior, `new Array(number)` tiene todos los elementos `undefined`. -To evade such surprises, we usually use square brackets, unless we really know what we're doing. +Para evitar sorpresas solemos usar corchetes, salvo que sepamos lo que estamos haciendo. -## Multidimensional arrays +## Arrays multidimensionales -Arrays can have items that are also arrays. We can use it for multidimensional arrays, for example to store matrices: +Los arrays pueden tener items que a su vez sean arrays. Podemos usarlos como arrays multidimensionales, por ejemplo para almacenar matrices: ```js run let matrix = [ @@ -394,14 +394,14 @@ let matrix = [ [7, 8, 9] ]; -alert( matrix[1][1] ); // 5, the central element +alert( matrix[1][1] ); // 5, el elemento central ``` ## toString -Arrays have their own implementation of `toString` method that returns a comma-separated list of elements. +Los arrays tienen su propia implementación del método `toString` que devuelve un lista de elementos separados por coma. -For instance: +Por ejemplo: ```js run @@ -411,7 +411,7 @@ alert( arr ); // 1,2,3 alert( String(arr) === '1,2,3' ); // true ``` -Also, let's try this: +Probemos esto también: ```js run alert( [] + 1 ); // "1" @@ -419,9 +419,9 @@ alert( [1] + 1 ); // "11" alert( [1,2] + 1 ); // "1,21" ``` -Arrays do not have `Symbol.toPrimitive`, neither a viable `valueOf`, they implement only `toString` conversion, so here `[]` becomes an empty string, `[1]` becomes `"1"` and `[1,2]` becomes `"1,2"`. +Los arrays no tienen `Symbol.toPrimitive` ni un viable `valueOf`, ellos implementan la conversión `toString` solamente, así `[]` se vuelve una cadena vacía, `[1]` se vuelve `"1"` y `[1,2]` se vuelve `"1,2"`. -When the binary plus `"+"` operator adds something to a string, it converts it to a string as well, so the next step looks like this: +Cuando el operador binario más `"+"` suma algo a una cadena, lo convierte a cadena también, entonces lo siguiente es ve así: ```js run alert( "" + 1 ); // "1" @@ -429,35 +429,35 @@ alert( "1" + 1 ); // "11" alert( "1,2" + 1 ); // "1,21" ``` -## Summary +## Resumen -Array is a special kind of object, suited to storing and managing ordered data items. +Los arrays son una clase especial de objeto, adecuados para almacenar y manejar items de datos ordenados. -- The declaration: +- La declaración: ```js - // square brackets (usual) + // corchetes (usual) let arr = [item1, item2...]; - // new Array (exceptionally rare) + // new Array (excepcionalmente raro) let arr = new Array(item1, item2...); ``` - The call to `new Array(number)` creates an array with the given length, but without elements. + Un llamado a `new Array(number)` crea un array con el largo dado, pero sin elementos. -- The `length` property is the array length or, to be precise, its last numeric index plus one. It is auto-adjusted by array methods. -- If we shorten `length` manually, the array is truncated. +- La propiedad `length` es el largo del array o, para ser preciso, el último índice numérico más uno. Se autoajusta al usar los métodos de array. +- Si acortamos `length` manualmente, el array es truncado. -We can use an array as a deque with the following operations: +Podemos usar un array como "bicola" con las siguientes operaciones: -- `push(...items)` adds `items` to the end. -- `pop()` removes the element from the end and returns it. -- `shift()` removes the element from the beginning and returns it. -- `unshift(...items)` adds `items` to the beginning. +- `push(...items)` agrega `items` al final. +- `pop()` remueve el elemento del final y lo devuelve. +- `shift()` remueve el elemento del principio y lo devuelve. +- `unshift(...items)` agrega `items` al principio. -To loop over the elements of the array: - - `for (let i=0; i. +Volveremos a los arrays y estudiaremos más métodos para agregar, quitar, extraer elementos y ordenar arrays en el capítulo . From 5314f8fa36c961cab8354c5b131cddf11e3d012e Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 06:09:34 -0300 Subject: [PATCH 02/28] Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/10-maximal-subarray/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md index ed556e738..d71d449a6 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md @@ -2,7 +2,7 @@ Podemos calcular todas las subsumas. -La más simple forma es tomar cada elemento y calcular las sumas de todos los subarrays que comienzan con él. +La forma más simple es tomar cada elemento y calcular las sumas de todos los subarrays que comienzan con él. Por ejemplo, para `[-1, 2, 3, -9, 11]`: From b3a0cc0260981470ab354b0707f083730331a927 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 07:50:29 -0300 Subject: [PATCH 03/28] Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/10-maximal-subarray/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md index d71d449a6..2ef579f95 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md @@ -57,7 +57,7 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6 alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100 ``` -La solución tiene una complejidad 2 en notación Landau (coste respecto al tiempo) [O(n2)](https://es.wikipedia.org/wiki/Notaci%C3%B3n_de_Landau). Es decir, si multiplicamos el tamaño del array por 2, el tiempo del algoritmo se multiplicará por 4. +La solución tiene una complejidad 2 en notación Landau [O(n2)](https://es.wikipedia.org/wiki/Notaci%C3%B3n_de_Landau) (coste respecto al tiempo). Es decir, si multiplicamos el tamaño del array por 2, el tiempo del algoritmo se multiplicará por 4. Para arrays muy grandes (1000, 10000 o más items) tales algoritmos llevarán a una severa lentitud. From af2e2a0c144ebcec969b2c1d88666eb0b966f811 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:14:25 -0300 Subject: [PATCH 04/28] Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/10-maximal-subarray/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md index 2ef579f95..43a03d4e3 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md @@ -72,7 +72,7 @@ function getMaxSubSum(arr) { let maxSum = 0; let partialSum = 0; - for (let item of arr) { // para cada item de arr + for (let item of arr) { // por cada item de arr partialSum += item; // se lo suma a partialSum maxSum = Math.max(maxSum, partialSum); // registra el máximo if (partialSum < 0) partialSum = 0; // cero si se vuelve negativo From a373976bae20c01301c5b54a0fc6e51223b0ab89 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:17:19 -0300 Subject: [PATCH 05/28] Update 1-js/05-data-types/04-array/5-array-input-sum/task.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Maldito teclado. La s me está fallando. Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/5-array-input-sum/task.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/5-array-input-sum/task.md b/1-js/05-data-types/04-array/5-array-input-sum/task.md index f95476111..b5cfa4947 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/task.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/task.md @@ -10,6 +10,6 @@ Escribe una función `sumInput()` que: - Termine de pedirlos cuando el usuario entre un valor no numérico, una cadena vacía, o presione "Escape". - Calcule y devuelva la suma de los items del array. -P.D. Un cero `0` es un número válido, por favor no detenga los ingresos con el cero. +P.D. Un cero `0` es un número válido, por favor no detengas los ingresos con el cero. [demo] From baa16d72f66c01e004b799e50ec394c16c901df0 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:18:36 -0300 Subject: [PATCH 06/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index d046c8cc4..aa7f2dec3 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -419,7 +419,7 @@ alert( [1] + 1 ); // "11" alert( [1,2] + 1 ); // "1,21" ``` -Los arrays no tienen `Symbol.toPrimitive` ni un viable `valueOf`, ellos implementan la conversión `toString` solamente, así `[]` se vuelve una cadena vacía, `[1]` se vuelve `"1"` y `[1,2]` se vuelve `"1,2"`. +Los arrays no tienen `Symbol.toPrimitive` ni un `valueOf` viable, ellos implementan la conversión `toString` solamente, así `[]` se vuelve una cadena vacía, `[1]` se vuelve `"1"` y `[1,2]` se vuelve `"1,2"`. Cuando el operador binario más `"+"` suma algo a una cadena, lo convierte a cadena también, entonces lo siguiente es ve así: From 71793c90bf823732061a0f06950f00ed8d3a927f Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:19:07 -0300 Subject: [PATCH 07/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index aa7f2dec3..005eedb38 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -443,7 +443,7 @@ Los arrays son una clase especial de objeto, adecuados para almacenar y manejar let arr = new Array(item1, item2...); ``` - Un llamado a `new Array(number)` crea un array con el largo dado, pero sin elementos. + Un llamado a `new Array(number)` crea un array con la longitud dada, pero sin elementos. - La propiedad `length` es el largo del array o, para ser preciso, el último índice numérico más uno. Se autoajusta al usar los métodos de array. - Si acortamos `length` manualmente, el array es truncado. From 1a517fdf0ad89efe2c5bb941232d83c00783e432 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:20:27 -0300 Subject: [PATCH 08/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 005eedb38..f0957845c 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -421,7 +421,7 @@ alert( [1,2] + 1 ); // "1,21" Los arrays no tienen `Symbol.toPrimitive` ni un `valueOf` viable, ellos implementan la conversión `toString` solamente, así `[]` se vuelve una cadena vacía, `[1]` se vuelve `"1"` y `[1,2]` se vuelve `"1,2"`. -Cuando el operador binario más `"+"` suma algo a una cadena, lo convierte a cadena también, entonces lo siguiente es ve así: +Cuando el operador binario más `"+"` suma algo a una cadena, lo convierte a cadena también, entonces lo siguiente se ve así: ```js run alert( "" + 1 ); // "1" From a73a2042c417ef29c1241f506378500b4c2a7bd0 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:20:52 -0300 Subject: [PATCH 09/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index f0957845c..659a70bc5 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -445,7 +445,7 @@ Los arrays son una clase especial de objeto, adecuados para almacenar y manejar Un llamado a `new Array(number)` crea un array con la longitud dada, pero sin elementos. -- La propiedad `length` es el largo del array o, para ser preciso, el último índice numérico más uno. Se autoajusta al usar los métodos de array. +- La propiedad `length` es la longitud del array o, para ser preciso, el último índice numérico más uno. Se autoajusta al usar los métodos de array. - Si acortamos `length` manualmente, el array es truncado. Podemos usar un array como "bicola" con las siguientes operaciones: From e88e22ae44ec943bf91bc81efc4a17b863b5ef7f Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:21:41 -0300 Subject: [PATCH 10/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 659a70bc5..079b8ebdd 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -446,7 +446,7 @@ Los arrays son una clase especial de objeto, adecuados para almacenar y manejar Un llamado a `new Array(number)` crea un array con la longitud dada, pero sin elementos. - La propiedad `length` es la longitud del array o, para ser preciso, el último índice numérico más uno. Se autoajusta al usar los métodos de array. -- Si acortamos `length` manualmente, el array es truncado. +- Si acortamos `length` manualmente, el array se trunca. Podemos usar un array como "bicola" con las siguientes operaciones: From fef7302484a852405bcb94f56fb4fdec68bb06d3 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:22:19 -0300 Subject: [PATCH 11/28] Update 1-js/05-data-types/04-array/5-array-input-sum/task.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/5-array-input-sum/task.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/5-array-input-sum/task.md b/1-js/05-data-types/04-array/5-array-input-sum/task.md index b5cfa4947..f863015f0 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/task.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/task.md @@ -7,7 +7,7 @@ importance: 4 Escribe una función `sumInput()` que: - Pida al usuario valores usando `prompt` y los almacene en el array. -- Termine de pedirlos cuando el usuario entre un valor no numérico, una cadena vacía, o presione "Escape". +- Termine de pedirlos cuando el usuario ingrese un valor no numérico, una cadena vacía, o presione "Escape". - Calcule y devuelva la suma de los items del array. P.D. Un cero `0` es un número válido, por favor no detengas los ingresos con el cero. From 93aedf5dad5ad67fa2d3b15278aa402c1052a4b5 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:23:30 -0300 Subject: [PATCH 12/28] Update 1-js/05-data-types/04-array/2-create-array/task.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/2-create-array/task.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/1-js/05-data-types/04-array/2-create-array/task.md b/1-js/05-data-types/04-array/2-create-array/task.md index c3989ba59..88a58c4ef 100644 --- a/1-js/05-data-types/04-array/2-create-array/task.md +++ b/1-js/05-data-types/04-array/2-create-array/task.md @@ -8,7 +8,7 @@ Tratemos 5 operaciones de array. 1. Crear un array `styles` con los items "Jazz" y "Blues". 2. Agregar "Rock-n-Roll" al final. -3. Reemplazar el valor en el medio por "Classics". Tu código para encontrar el valor medio debe funcionar con cualquier array de largo impar. +3. Reemplazar el valor en el medio por "Classics". Tu código para encontrar el valor medio debe funcionar con cualquier array de longitud impar. 4. Quitar el primer valor del array y mostrarlo. 5. Anteponer `Rap` y `Reggae` al array. @@ -21,4 +21,3 @@ Jazz, Classics, Rock-n-Roll Classics, Rock-n-Roll Rap, Reggae, Classics, Rock-n-Roll ``` - From cc3750ca579e2e4bf933c1bcb8996578d834e7c9 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:24:29 -0300 Subject: [PATCH 13/28] Update 1-js/05-data-types/04-array/3-call-array-this/solution.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/3-call-array-this/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/3-call-array-this/solution.md b/1-js/05-data-types/04-array/3-call-array-this/solution.md index e4760ae01..e5114a1f8 100644 --- a/1-js/05-data-types/04-array/3-call-array-this/solution.md +++ b/1-js/05-data-types/04-array/3-call-array-this/solution.md @@ -1,4 +1,4 @@ -El llamado a `arr[2]()` es sintácticamente el buen y viejo `obj[method]()`, el el rol de `obj` tenemos `arr`, y en el rol de `method` tenemos `2`. +El llamado a `arr[2]()` es sintácticamente el buen y viejo `obj[method]()`, en el rol de `obj` tenemos `arr`, y en el rol de `method` tenemos `2`. Entonces tenemos una llamada a función `arr[2]` como un método de objeto. Naturalmente, recibe `this` referenciando el objeto `arr` y su salida es el array: From c2f4f6712b9dfd3f0aa615cf511662a3c471b93a Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:26:07 -0300 Subject: [PATCH 14/28] Update 1-js/05-data-types/04-array/3-call-array-this/task.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/3-call-array-this/task.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/1-js/05-data-types/04-array/3-call-array-this/task.md b/1-js/05-data-types/04-array/3-call-array-this/task.md index f97de8eb9..82311c35a 100644 --- a/1-js/05-data-types/04-array/3-call-array-this/task.md +++ b/1-js/05-data-types/04-array/3-call-array-this/task.md @@ -4,7 +4,7 @@ importance: 5 # LLamados en un contexto de array -¿Cuál es el resultado?¿Por qué? +¿Cuál es el resultado y por qué? ```js let arr = ["a", "b"]; @@ -15,4 +15,3 @@ arr.push(function() { arr[2](); // ? ``` - From 05a06187a4f176b4a919461420bd92bd6e5a371a Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:28:26 -0300 Subject: [PATCH 15/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 079b8ebdd..f5213bc39 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -47,7 +47,7 @@ fruits[2] = 'Pear'; // ahora ["Apple", "Orange", "Pear"] fruits[3] = 'Lemon'; // ahora ["Apple", "Orange", "Pear", "Lemon"] ``` -La cuenta total de elementos en el array es su largo `length`: +La cuenta total de elementos en el array es su longitud `length`: ```js run let fruits = ["Apple", "Orange", "Plum"]; From 383249ddf018ac3b0d02f2fbd858337987de6738 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:28:44 -0300 Subject: [PATCH 16/28] Update 1-js/05-data-types/04-array/5-array-input-sum/solution.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/5-array-input-sum/solution.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/1-js/05-data-types/04-array/5-array-input-sum/solution.md b/1-js/05-data-types/04-array/5-array-input-sum/solution.md index 9b9a4d9e0..b137c7971 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/solution.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/solution.md @@ -8,7 +8,7 @@ function sumInput() { while (true) { - let value = prompt("¿Un número por favor?", 0); + let value = prompt("Un número, por favor...", 0); // ¿Debemos cancelar? if (value === "" || value === null || !isFinite(value)) break; @@ -25,4 +25,3 @@ function sumInput() { alert( sumInput() ); ``` - From f122d1ec980c1d461f0783c723879b391b11c253 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:34:51 -0300 Subject: [PATCH 17/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index f5213bc39..ac6144022 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -23,7 +23,7 @@ Casi siempre se usa la segunda. Podemos suministrar elementos iniciales entre lo let fruits = ["Apple", "Orange", "Plum"]; ``` -Los elementoss del array están numerados, comenzando desde cero. +Los elementos del array están numerados comenzando desde cero. Podemos obtener un elemento por su número entre corchetes: From 8fdb93a256dc45daba4ed0bd956c7375ca3dbfac Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:42:50 -0300 Subject: [PATCH 18/28] Update 1-js/05-data-types/04-array/article.md ocioso... pero me da igual Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index ac6144022..8f6d7fc16 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -159,7 +159,7 @@ En ciencias de la computación la estructura de datos que permite esto se denomi ```js run let fruits = ["Apple", "Orange", "Pear"]; - alert( fruits.shift() ); // quita Apple y lo muestra + alert( fruits.shift() ); // quita Apple y lo muestra en una alerta alert( fruits ); // Orange, Pear ``` From 726df5604a61302055cad4db1329b43db8d2e9ee Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:47:59 -0300 Subject: [PATCH 19/28] Update 1-js/05-data-types/04-array/article.md AAAAHHHHHHH!!!! Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 8f6d7fc16..f36115ac6 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -189,7 +189,7 @@ alert( fruits ); ## Internamente -Un array es una clase especial de objeto. Los corchetes usados para acceder a una propiedad `arr[0]` vienen de la sintaxi de objeto. Son esencialmente lo mismo que `obj[key]`, donde `arr` es el objeto mientras los números son usados como claves. +Un array es una clase especial de objeto. Los corchetes usados para acceder a una propiedad `arr[0]` vienen de la sintaxis de objeto. Son esencialmente lo mismo que `obj[key]`, donde `arr` es el objeto mientras los números son usados como claves. Ellos extienden los objetos proveyendo métodos especiales para trabajar con colecciones ordenadas de datos y también la propiedad `length`. Pero el corazón es aún un objeto. From b3e45852723293b99230b8d78f001903c036305e Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:51:06 -0300 Subject: [PATCH 20/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index f36115ac6..4873ca725 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -191,7 +191,7 @@ alert( fruits ); Un array es una clase especial de objeto. Los corchetes usados para acceder a una propiedad `arr[0]` vienen de la sintaxis de objeto. Son esencialmente lo mismo que `obj[key]`, donde `arr` es el objeto mientras los números son usados como claves. -Ellos extienden los objetos proveyendo métodos especiales para trabajar con colecciones ordenadas de datos y también la propiedad `length`. Pero el corazón es aún un objeto. +Ellos extienden los objetos proveyendo métodos especiales para trabajar con colecciones ordenadas de datos y también la propiedad `length`. Pero en el corazón es aún un objeto. Recuerda, hay solo 7 tipos basicos en JavaScript. Array es un objeto y se comporta como un objeto.. From 2f951b1346f93f735b9442b04ebc6fa72176410e Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:52:56 -0300 Subject: [PATCH 21/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 4873ca725..a3c9976b5 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -253,7 +253,7 @@ La operación `shift` debe hacer 3 cosas: 1. Remover el elemento con índice `0`. 2. Mover todos lo elementos hacia la izquierda y renumerarlos: desde el índice `1` a `0`, de `2` a `1` y así sucesivamente. -3. Actualizar el largo: la propiedad `length`. +3. Actualizar la longitud: la propiedad `length`. ![](array-shift.svg) From 785ff5280094d9c68762c5ca80789394a7e29822 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:54:07 -0300 Subject: [PATCH 22/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index a3c9976b5..a577b488f 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -329,7 +329,7 @@ En general, no deberíamos usar `for..in` en arrays. La propiedad `length` automáticamente se actualiza cuando se modifica el array. Para ser precisos, no es la cuenta de valores del array sino el mayor índice más uno. -Por ejemplo, un elemento simple con un índice grande da un largo grande: +Por ejemplo, un elemento simple con un índice grande da una longitud grande: ```js run let fruits = []; From fe7c1bf21e9c66df7252773e4a8213815a80e159 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:59:05 -0300 Subject: [PATCH 23/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index a577b488f..396126cb4 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -342,7 +342,7 @@ Nota que usualmente no usamos arrays de este modo. Otra cosa interesante acerca de la propiedad `length` es que se puede sobrescribir. -Si la incrementamos manualmente, nada interesante ocurre. Pero si la decrementamos, el array es truncado. El proceso es irreversible, aquí el ejemplo: +Si la incrementamos manualmente, nada interesante ocurre. Pero si la decrementamos, el array se trunca. El proceso es irreversible, aquí el ejemplo: ```js run let arr = [1, 2, 3, 4, 5]; From 214685f8b18a347132ff0fd4413f16975bd0daee Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 08:59:32 -0300 Subject: [PATCH 24/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 396126cb4..3016e9b0e 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -350,7 +350,7 @@ let arr = [1, 2, 3, 4, 5]; arr.length = 2; // truncamos a 2 elementos alert( arr ); // [1, 2] -arr.length = 5; // reponemos el largo length +arr.length = 5; // reponemos la longitud length alert( arr[3] ); // undefined: el valor no se recupera ``` From db4e7fb52e7ac968618e6a116c35ad98391e53eb Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 09:01:38 -0300 Subject: [PATCH 25/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 3016e9b0e..5bdb39fd1 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -367,7 +367,7 @@ let arr = *!*new Array*/!*("Apple", "Pear", "etc"); Es raramente usada porque con corchetes `[]` es más corto. También hay una característica peculiar con ella. -Si `new Array` es llamado con un único argumento numérico, se crea un array *sin items, pero con el largo "length" dado*. +Si `new Array` es llamado con un único argumento numérico, se crea un array *sin items, pero con la longitud "length" dada*. Veamos cómo uno puede dispararse en el pie: From 778666a0c4d200d12c332a14eacbb2a13ba4c1c2 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 09:19:36 -0300 Subject: [PATCH 26/28] Update article.md --- 1-js/05-data-types/04-array/article.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 5bdb39fd1..8dcec5299 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -121,7 +121,7 @@ Una pila es usualmente mostrada como un mazo de cartas, donde las nuevas cartas Para las pilas, la última introducida es la primera en ser recibida, en inglés esto es llamado principio LIFO (Last-In-First-Out, última en entrar primera en salir). Para las colas, tenemos FIFO (First-In-First-Out primera en entrar, primera en salir). -Los arrays en JavaScript pueden trabajar como colas o pilas. Ellos permiten agregar o quitar elementos a y desde el principio o a y desde el final. +Los arrays en JavaScript pueden trabajar como colas o pilas. Ellos permiten agregar/quitar elementos al/del principio o al/del final. En ciencias de la computación la estructura de datos que permite esto se denomina cola de doble extremo o [bicola](https://es.wikipedia.org/wiki/Bicola). @@ -133,7 +133,7 @@ En ciencias de la computación la estructura de datos que permite esto se denomi ```js run let fruits = ["Apple", "Orange", "Pear"]; - alert( fruits.pop() ); // quita "Pear" y lo muestra + alert( fruits.pop() ); // quita "Pear" y lo muestra en un alert alert( fruits ); // Apple, Orange ``` @@ -187,7 +187,7 @@ fruits.unshift("Pineapple", "Lemon"); alert( fruits ); ``` -## Internamente +## Interiores Un array es una clase especial de objeto. Los corchetes usados para acceder a una propiedad `arr[0]` vienen de la sintaxis de objeto. Son esencialmente lo mismo que `obj[key]`, donde `arr` es el objeto mientras los números son usados como claves. @@ -218,7 +218,7 @@ Por ejemplo, técnicamente podemos hacer esto: ```js let fruits = []; // crea un array -fruits[99999] = 5; // asigna una propiedad con un índice mucho mayor que su largo +fruits[99999] = 5; // asigna una propiedad con un índice mucho mayor que su longitud fruits.age = 25; // crea una propiedad con un nombre arbitrario ``` @@ -376,7 +376,7 @@ let arr = new Array(2); // ¿Creará un array de [2]? alert( arr[0] ); // undefined! sin elementos. -alert( arr.length ); // largo 2 +alert( arr.length ); // longitud 2 ``` En el código anterior, `new Array(number)` tiene todos los elementos `undefined`. From bcb2dc41474f5be2117cfdcbabc68f14a6be7739 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 21 Jul 2020 23:10:20 -0300 Subject: [PATCH 27/28] Update 1-js/05-data-types/04-array/article.md Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 8dcec5299..c15c93197 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -159,7 +159,7 @@ En ciencias de la computación la estructura de datos que permite esto se denomi ```js run let fruits = ["Apple", "Orange", "Pear"]; - alert( fruits.shift() ); // quita Apple y lo muestra en una alerta + alert( fruits.shift() ); // quita Apple y lo muestra en un alert alert( fruits ); // Orange, Pear ``` From 6a6b3f86a81b9418b01fcdb2dd09ea94f4bb84da Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Wed, 22 Jul 2020 02:03:57 -0300 Subject: [PATCH 28/28] Update 1-js/05-data-types/04-array/10-maximal-subarray/solution.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NO creo que sea mejor "actual". Pero busqué en el repo, y fue lo usado. Sea por correcto o por convención, pensando en quien aprende, prefiero la homogeneidad. Va ACTUAL. Co-authored-by: Maksumi Murakami --- 1-js/05-data-types/04-array/10-maximal-subarray/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md index 43a03d4e3..00ef1c420 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md @@ -63,7 +63,7 @@ Para arrays muy grandes (1000, 10000 o más items) tales algoritmos llevarán a # Solución rápida -Recorramos el array y registremos la suma parcial corriente de los elementos en la variable `s`. Si `s` se vuelve cero en algún punto, le asignamos `s=0`. El máximo entre todas las sumas parciales `s` será la respuesta. +Recorramos el array y registremos la suma parcial actual de los elementos en la variable `s`. Si `s` se vuelve cero en algún punto, le asignamos `s=0`. El máximo entre todas las sumas parciales `s` será la respuesta. Si la descripción te resulta demasiado vaga, por favor mira el código. Es bastante corto: