Skip to content

Commit 04b64e8

Browse files
authored
Merge pull request #108 from Arnau-Ninerola/master
Translated Comments, Polyfills and index
2 parents aec1a3a + a4f4473 commit 04b64e8

File tree

4 files changed

+111
-114
lines changed

4 files changed

+111
-114
lines changed
Lines changed: 84 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
1-
# Comments
1+
# Comentarios
22

3-
As we know from the chapter <info:structure>, comments can be single-line: starting with `//` and multiline: `/* ... */`.
3+
Como hemos aprendido en el capítulo <info:structure>, los comentarios pueden ser de una sola línea: comenzando con `//` y de múltiples líneas: `/* ... */`.
44

5-
We normally use them to describe how and why the code works.
5+
Normalmente los usamos para describir cómo y por qué el código funciona.
66

7-
At first sight, commenting might be obvious, but novices in programming often use them wrongly.
7+
A primera vista, los comentarios pueden ser obvios, pero los principiantes en programación generalmente los usan incorrectamente.
88

9-
## Bad comments
9+
## Comentarios incorrectos
1010

11-
Novices tend to use comments to explain "what is going on in the code". Like this:
11+
Los rincipiantes tienden a utilizar los comentarios para explicar "lo que está pasando en el código". Así:
1212

1313
```js
14-
// This code will do this thing (...) and that thing (...)
15-
// ...and who knows what else...
16-
very;
17-
complex;
18-
code;
14+
// Este código hará esto (...) y esto (...)
15+
// ...y quién sabe qué más...
16+
código;
17+
muy;
18+
complejo;
1919
```
2020

21-
But in good code, the amount of such "explanatory" comments should be minimal. Seriously, the code should be easy to understand without them.
21+
Pero en un buen código, la cantidad de comentarios "explicativos" debería ser mínima. En serio, el código debería ser fácil de entender sin ellos.
2222

23-
There's a great rule about that: "if the code is so unclear that it requires a comment, then maybe it should be rewritten instead".
23+
Existe una fantástica regla al respeto: "si el código es tan poco claro que necesita un comentario, tal vez en su lugar debería ser reescrito.".
2424

25-
### Recipe: factor out functions
25+
### Receta: funciones externas
2626

27-
Sometimes it's beneficial to replace a code piece with a function, like here:
27+
A veces es beneficioso reemplazar trozos de código con funciones, como aquí:
2828

2929
```js
3030
function showPrimes(n) {
3131
nextPrime:
3232
for (let i = 2; i < n; i++) {
3333

3434
*!*
35-
// check if i is a prime number
35+
// comprobar si i es un número primo
3636
for (let j = 2; j < i; j++) {
3737
if (i % j == 0) continue nextPrime;
3838
}
@@ -43,8 +43,7 @@ function showPrimes(n) {
4343
}
4444
```
4545

46-
The better variant, with a factored out function `isPrime`:
47-
46+
La mejor variante, con una función externa `isPrime`:
4847

4948
```js
5049
function showPrimes(n) {
@@ -65,21 +64,21 @@ function isPrime(n) {
6564
}
6665
```
6766

68-
Now we can understand the code easily. The function itself becomes the comment. Such code is called *self-descriptive*.
67+
Ahora podemos entender el código fácilmente. La propia función se convierte en comentario. Este tipo de código se le llama *auto descriptivo*.
6968

70-
### Recipe: create functions
69+
### Receta: crear funciones
7170

72-
And if we have a long "code sheet" like this:
71+
Y si tenemos una larga "hoja de código" como esta:
7372

7473
```js
75-
// here we add whiskey
74+
// aquí añadimos whiskey
7675
for(let i = 0; i < 10; i++) {
7776
let drop = getWhiskey();
7877
smell(drop);
7978
add(drop, glass);
8079
}
8180

82-
// here we add juice
81+
// aquí añadimos zumo
8382
for(let t = 0; t < 3; t++) {
8483
let tomato = getTomato();
8584
examine(tomato);
@@ -90,7 +89,7 @@ for(let t = 0; t < 3; t++) {
9089
// ...
9190
```
9291

93-
Then it might be a better variant to refactor it into functions like:
92+
Entonces, una versión mejor puede ser reescribirlo en funciones de esta manera:
9493

9594
```js
9695
addWhiskey(glass);
@@ -111,70 +110,70 @@ function addJuice(container) {
111110
}
112111
```
113112

114-
Once again, functions themselves tell what's going on. There's nothing to comment. And also the code structure is better when split. It's clear what every function does, what it takes and what it returns.
115-
116-
In reality, we can't totally avoid "explanatory" comments. There are complex algorithms. And there are smart "tweaks" for purposes of optimization. But generally we should try to keep the code simple and self-descriptive.
117-
118-
## Good comments
119-
120-
So, explanatory comments are usually bad. Which comments are good?
121-
122-
Describe the architecture
123-
: Provide a high-level overview of components, how they interact, what's the control flow in various situations... In short -- the bird's eye view of the code. There's a special language [UML](http://wikipedia.org/wiki/Unified_Modeling_Language) to build high-level architecture diagrams explaining the code. Definitely worth studying.
124-
125-
Document function parameters and usage
126-
: There's a special syntax [JSDoc](http://en.wikipedia.org/wiki/JSDoc) to document a function: usage, parameters, returned value.
127-
128-
For instance:
129-
```js
130-
/**
131-
* Returns x raised to the n-th power.
132-
*
133-
* @param {number} x The number to raise.
134-
* @param {number} n The power, must be a natural number.
135-
* @return {number} x raised to the n-th power.
136-
*/
137-
function pow(x, n) {
138-
...
139-
}
140-
```
141-
142-
Such comments allow us to understand the purpose of the function and use it the right way without looking in its code.
113+
De nuevo, la propias funciones nos dicen qué está pasando. No hay nada que comentar. Y además, la estructura del código es mejor cuando está dividida. Queda claro qué hace cada función, qué necesita y qué retorna.
143114

144-
By the way, many editors like [WebStorm](https://www.jetbrains.com/webstorm/) can understand them as well and use them to provide autocomplete and some automatic code-checking.
115+
En realidad, no podemos evitar totalmente los comentarios "explicativos". Existen algoritmos complejos. Y existen "trucos" ingeniosos con el propósito de optimizar. Pero generalmente, tenemos que intentar mantener el código simple y auto descriptivo.
145116

146-
Also, there are tools like [JSDoc 3](https://github.com/jsdoc3/jsdoc) that can generate HTML-documentation from the comments. You can read more information about JSDoc at <http://usejsdoc.org/>.
117+
## Comentarios correctos
147118

148-
Why is the task solved this way?
149-
: What's written is important. But what's *not* written may be even more important to understand what's going on. Why is the task solved exactly this way? The code gives no answer.
119+
Entonces, los comentarios explicativos suelen ser incorrectos. ¿Qué comentarios son correctos?
150120

151-
If there are many ways to solve the task, why this one? Especially when it's not the most obvious one.
121+
Describe la arquitectura
122+
: Proporcionan una descripción general de alto nivel de los componentes, cómo interactúan, cuál es el flujo de control en diversas situaciones... En resumen -- la vista panorámica del código. Hay un lenguaje de diagramas especial [UML](https://es.wikipedia.org/wiki/Lenguaje_unificado_de_modelado) para diagramas de alto nivel. Definitivamente vale la pena estudiarlo.
152123

153-
Without such comments the following situation is possible:
154-
1. You (or your colleague) open the code written some time ago, and see that it's "suboptimal".
155-
2. You think: "How stupid I was then, and how much smarter I'm now", and rewrite using the "more obvious and correct" variant.
156-
3. ...The urge to rewrite was good. But in the process you see that the "more obvious" solution is actually lacking. You even dimly remember why, because you already tried it long ago. You revert to the correct variant, but the time was wasted.
124+
Documenta la utilización de una función
125+
: Hay una sintaxis especial [JSDoc](https://en.wikipedia.org/wiki/JSDoc) para documentar una función: utilización, parámetros, valor devuelto.
157126

158-
Comments that explain the solution are very important. They help to continue development the right way.
159-
160-
Any subtle features of the code? Where they are used?
161-
: If the code has anything subtle and counter-intuitive, it's definitely worth commenting.
162-
163-
## Summary
164-
165-
An important sign of a good developer is comments: their presence and even their absence.
166-
167-
Good comments allow us to maintain the code well, come back to it after a delay and use it more effectively.
168-
169-
**Comment this:**
170-
171-
- Overall architecture, high-level view.
172-
- Function usage.
173-
- Important solutions, especially when not immediately obvious.
174-
175-
**Avoid comments:**
176-
177-
- That tell "how code works" and "what it does".
178-
- Put them in only if it's impossible to make the code so simple and self-descriptive that it doesn't require them.
179-
180-
Comments are also used for auto-documenting tools like JSDoc3: they read them and generate HTML-docs (or docs in another format).
127+
Por ejemplo:
128+
```js
129+
/**
130+
* Devuelve x elevado a la potencia de n.
131+
*
132+
* @param {number} x El número a elevar.
133+
* @param {number} n La potencia, debe ser un número natural.
134+
* @return {number} x elevado a la potencia de n.
135+
*/
136+
function pow(x, n) {
137+
...
138+
}
139+
```
140+
141+
Estos tipos de comentarios nos permiten entender el propósito de la función y cómo usarla de la manera correcta sin mirar su código.
142+
143+
Por cierto, muchos editores como [WebStorm](https://www.jetbrains.com/webstorm/) también pueden entenderlos y usarlos para proveer auto completado y algún tipo de verificación automática para el código.
144+
145+
Además, existen herramientas como [JSDoc](https://github.com/jsdoc3/jsdoc) que pueden generar documentación en formato HTML de los comentarios. Puedes leer más información sobre JSDoc aquí <http://usejsdoc.org/>.
146+
147+
¿Por qué se resuelve de esa manera?
148+
: Lo que está escrito es importante. Pero lo que *no* está escrito puede ser aún más importante para entender qué está pasando. ¿Por qué resuelven la tarea exactamente de esa manera? El código no nos da ninguna respuesta.
149+
150+
Si hay muchas maneras de resolver el problema, ¿por qué esta? Especialmente cuando no es la más obvia.
151+
152+
Sin dichos comentarios, las siguientes situaciones son posibles:
153+
1. Tú (o tu compañero) abres el código escrito hace ya algún tiempo, y te das cuenta de que es "subóptimo".
154+
2. Piensas: "Que estúpido que era antes, y que inteligente que soy ahora", y lo reescribes utilizando la variante "más obvia y correcta".
155+
3. ...El impulso de reescribir era bueno. Pero en el proceso ves que la solución "más obvia" en realidad falla. Incluso recuerdas vagamente el porqué, porque ya lo intentaste hace mucho. Vuelves a la variante correcta pero has estado perdiendo el tiempo.
156+
157+
Los comentarios que explican la solución correcta son muy importantes. Nos ayudan a continuar el desarrollo de forma correcta.
158+
159+
¿Alguna característica sutil del código? ¿Dónde se usan?
160+
: Si el código tiene algo sutil y contraintuitivo, definitivamente vale la pena comentarlo.
161+
162+
## Resumen
163+
164+
Una señal importante de un buen desarrollador son los comentarios: su presencia e incluso su ausencia.
165+
166+
Los buenos comentarios nos permiten mantener bien el código, volver después de un retraso y usarlo de manera más efectiva.
167+
168+
**Comenta esto:**
169+
170+
- Arquitectura en general, vista de alto nivel.
171+
- Utilización de funciones.
172+
- Soluciones importantes, especialmente cuando no son inmediatamente obvias.
173+
174+
**Evita comentarios:**
175+
176+
- Que explican "cómo funciona el código" y "qué hace".
177+
- Escríbelos solo si es imposible escribir el código de manera tan simple y auto descriptiva que no los necesite.
178+
179+
Los comentarios también son usados para herramientas de auto documentación como JSDoc3: los leen y generan documentación en HTML (o documentos en otros formatos).
Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,52 @@
1-
21
# Polyfills
32

4-
The JavaScript language steadily evolves. New proposals to the language appear regularly, they are analyzed and, if considered worthy, are appended to the list at <https://tc39.github.io/ecma262/> and then progress to the [specification](http://www.ecma-international.org/publications/standards/Ecma-262.htm).
3+
El lenguaje JavaScript evoluciona constantemente. Nuevas propuestas al lenguaje aparecen regularmente, son analizadas y, si se consideran valiosas, se agregan a la lista en <https://tc39.github.io/ecma262/> y luego avanzan hasta [specification](http://www.ecma-international.org/publications/standards/Ecma-262.htm).
54

6-
Teams behind JavaScript engines have their own ideas about what to implement first. They may decide to implement proposals that are in draft and postpone things that are already in the spec, because they are less interesting or just harder to do.
5+
Equipos detrás de intérpretes (engines) de JavaScript tienen sus propias ideas sobre qué implementar primero. Pueden decidir implementar propuestas que están en borrador y posponer cosas que ya están en la especificación, porque son menos interesantes o simplemente más difíciles de hacer.
76

8-
So it's quite common for an engine to implement only the part of the standard.
7+
Por lo tanto, es bastante común para un intérprete implementar solo la parte del estándar.
98

10-
A good page to see the current state of support for language features is <https://kangax.github.io/compat-table/es6/> (it's big, we have a lot to study yet).
9+
Una buena página para ver el estado actual de soporte para características del lenguaje es <https://kangax.github.io/compat-table/es6/> (es grande, todavía tenemos mucho que aprender).
1110

1211
## Babel
1312

14-
When we use modern features of the language, some engines may fail to support such code. Just as said, not all features are implemented everywhere.
13+
Cuando usamos características modernas del lenguaje, puede que algunos intérpretes no soporten dicho código. Como hemos dicho, no todas las características están implementadas en todas partes.
1514

16-
Here Babel comes to the rescue.
15+
Aquí Babel viene al rescate.
1716

18-
[Babel](https://babeljs.io) is a [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler). It rewrites modern JavaScript code into the previous standard.
17+
[Babel](https://babeljs.io) es un [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler). Reescribe código JavaScript moderno en el estándar anterior.
1918

20-
Actually, there are two parts in Babel:
19+
En realidad, hay dos partes en Babel:
2120

22-
1. First, the transpiler program, which rewrites the code. The developer runs it on their own computer. It rewrites the code into the older standard. And then the code is delivered to the website for users. Modern project build systems like [webpack](http://webpack.github.io/) provide means to run transpiler automatically on every code change, so that it's very easy to integrate into development process.
21+
1. Primero, el programa transpiler, que reescribe código. El desarrollador lo ejecuta en su propio ordenador. Reescribe el código al viejo estándar. Y entonces el código es entregado al navegador para los usuarios. Proyectos modernos para construcción de sistemas como [webpack](http://webpack.github.io/) o [brunch](http://brunch.io/), proporcionan medios para ejecutar el transpiler automáticamente en cada cambio al código, de modo que no implique ninguna perdida de tiempo de nuestra parte.
2322

24-
2. Second, the polyfill.
23+
2. Segundo, el polyfill.
2524

26-
New language features may include new built-in functions and syntax constructs.
27-
The transpiler rewrites the code, transforming syntax constructs into older ones. But as for new built-in functions, we need to implement them. JavaScript is a highly dynamic language, scripts may add/modify any functions, so that they behave according to the modern standard.
25+
El transpiler reescribe el código, por lo que se cubren las características de la sintaxis. Pero para funciones nuevas tenemos que escribir un script especial que las implemente. JavaScript es un lenguaje muy dinámico, puede que los scripts no solo agreguen nuevas funciones, sino también modifiquen las funciones incorporadas, para que actúen de forma correspondiente al estándar moderno.
2826

29-
A script that updates/adds new functions is called "polyfill". It "fills in" the gap and adds missing implementations.
27+
Existe el término "polyfill" para scripts que "llenan"(fill in) el vacío y agregan las implementaciones que faltan.
3028

31-
Two interesting polyfills are:
32-
- [core js](https://github.com/zloirock/core-js) that supports a lot, allows to include only needed features.
33-
- [polyfill.io](http://polyfill.io) service that provides a script with polyfills, depending on the features and user's browser.
29+
Dos polyfills interesantes son:
30+
- [babel polyfill](https://babeljs.io/docs/usage/polyfill/) que soporta mucho, pero es muy grande.
31+
- [polyfill.io](http://polyfill.io) servicio que nos permite cargar/construir polyfills bajo demanda, dependiendo de las características que necesitemos.
3432

35-
So, if we're going to use modern language features, a transpiler and a polyfill are necessary.
33+
Así que, si queremos usar características modernas del lenguaje, el transpiler y polyfill son necesarios.
3634

37-
## Examples in the tutorial
35+
## Ejemplos en el tutorial
3836

3937

4038
````online
41-
Most examples are runnable at-place, like this:
39+
La mayoría de ejemplos se pueden ejecutar en el sitio, así:
4240
4341
```js run
44-
alert('Press the "Play" button in the upper-right corner to run');
42+
alert('Presione el botón "Play" en la esquina superior derecha para ejecutar');
4543
```
4644
47-
Examples that use modern JS will work only if your browser supports it.
45+
Ejemplos que usan JS moderno solo funcionarán si tu navegador lo soporta.
4846
````
4947

5048
```offline
51-
As you're reading the offline version, in PDF examples are not runnable. In EPUB some of them can run.
49+
Como estás leyendo la verión offline, en PDF los ejemplos no se pueden ejecutar. En EPUB algunos pueden ejecutarse.
5250
```
5351

54-
Google Chrome is usually the most up-to-date with language features, good to run bleeding-edge demos without any transpilers, but other modern browsers also work fine.
52+
Generalmente, Google Chrome está actualizado con las últimas características del lenguaje, funciona bien para ejecutar demos con tecnología puntera sin ningún transpiler, pero otros navegadores modernos también funcionan bien.

1-js/03-code-quality/index.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
# Code quality
1+
# Calidad del código
22

3-
This chapter explains coding practices that we'll use further in the development.
3+
Este capitulo explica practicas en programación que usaremos durante el desarrollo.

1-js/index.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# The JavaScript language
1+
# El lenguaje JavaScript
22

3-
Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP.
3+
Aquí aprendemos JavaScript, empezando desde zero y pasando a conceptos avanzados como OOP (programación orientada a objetos).
44

5-
We concentrate on the language itself here, with the minimum of environment-specific notes.
5+
Aquí nos concentramos en el lenguaje en si mismo, con el mínimo de notas específicas del entorno.
66

0 commit comments

Comments
 (0)