chore(i18n,curriculum): processed translations (#42868)
This commit is contained in:
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b67
|
||||
title: Add Elements to the End of an Array Using concat Instead of push
|
||||
title: Adicione Elementos ao Final de um Array usando concat em vez de push
|
||||
challengeType: 1
|
||||
forumTopicId: 301226
|
||||
dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
|
||||
@ -8,50 +8,50 @@ dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
|
||||
|
||||
# --description--
|
||||
|
||||
Functional programming is all about creating and using non-mutating functions.
|
||||
Programação funcional é basicamente criar e utilizar funções que não modificam os seus argumentos.
|
||||
|
||||
The last challenge introduced the `concat` method as a way to combine arrays into a new one without mutating the original arrays. Compare `concat` to the `push` method. `push` adds an item to the end of the same array it is called on, which mutates that array. Here's an example:
|
||||
O último desafio mostrou como usar o método `concat` para criar um novo array a partir da combinação de outros sem modificar os originais. Compare os métodos `concat` e `push`. O `push` adiciona um item ao final do array à esquerda do `.`. Ele modifica o array. Um exemplo:
|
||||
|
||||
```js
|
||||
var arr = [1, 2, 3];
|
||||
arr.push([4, 5, 6]);
|
||||
```
|
||||
|
||||
`arr` would have a modified value of `[1, 2, 3, [4, 5, 6]]`, which is not the functional programming way.
|
||||
Modificamos `arr` para acomodar o novo valor: `[1, 2, 3, [4, 5, 6]]`. Mas não é assim que se faz em programação funcional.
|
||||
|
||||
`concat` offers a way to add new items to the end of an array without any mutating side effects.
|
||||
O `concat` nos oferece uma forma de adicionar novos itens ao final de um array sem alterá-lo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `nonMutatingPush` function so it uses `concat` to add `newItem` to the end of `original` instead of `push`. The function should return an array.
|
||||
Modifique a função `nonMutatingPush` de forma que ela use `concat` para adicionar `newItem` ao final de `original` em vez de `push`. A função deve retornar um array.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `concat` method.
|
||||
O seu código deve usar o método `concat`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.concat/g));
|
||||
```
|
||||
|
||||
Your code should not use the `push` method.
|
||||
O seu código não deve usar o método `push`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?push/g));
|
||||
```
|
||||
|
||||
The `first` array should not change.
|
||||
O primeiro array, `first`, não deve ser modificado.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
|
||||
```
|
||||
|
||||
The `second` array should not change.
|
||||
O segundo array, `second`, não deve ser modificado.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
|
||||
```
|
||||
|
||||
`nonMutatingPush([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
|
||||
`nonMutatingPush([1, 2, 3], [4, 5])` deve retornar `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6d
|
||||
title: Apply Functional Programming to Convert Strings to URL Slugs
|
||||
title: Use Programação Funcional para Converter Strings para <i>Slugs</i> de URL
|
||||
challengeType: 1
|
||||
forumTopicId: 301227
|
||||
dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
|
||||
@ -8,45 +8,45 @@ dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
|
||||
|
||||
# --description--
|
||||
|
||||
The last several challenges covered a number of useful array and string methods that follow functional programming principles. We've also learned about `reduce`, which is a powerful method used to reduce problems to simpler forms. From computing averages to sorting, any array operation can be achieved by applying it. Recall that `map` and `filter` are special cases of `reduce`.
|
||||
Os últimos desafios cobriram uma série de métodos úteis de strings e arrays que usam princípios de programação funcional. Também aprendemos o poderoso método `reduce`, que é usado para reduzir arrays a um único valor. Seja para calcular médias ou para ordenação, qualquer operação de array pode ser feita ao usá-lo. Lembre-se que `map` e `filter` são casos especiais de `reduce`.
|
||||
|
||||
Let's combine what we've learned to solve a practical problem.
|
||||
Vamos combinar o que aprendemos para resolver um problema prático.
|
||||
|
||||
Many content management sites (CMS) have the titles of a post added to part of the URL for simple bookmarking purposes. For example, if you write a Medium post titled `Stop Using Reduce`, it's likely the URL would have some form of the title string in it (`.../stop-using-reduce`). You may have already noticed this on the freeCodeCamp site.
|
||||
Muitos sites de gerenciamento de conteúdo (*content management sites*, CMS) usam o título das publicações como parte da URL para maior legibilidade. Por exemplo, se você publicar um artigo no Medium chamado `Pare de Usar reduce`, é provável que a URL use o título em sua composição: `.../pare-de-usar-reduce`. Talvez você já tenha percebido que acontece o mesmo no freeCodeCamp.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fill in the `urlSlug` function so it converts a string `title` and returns the hyphenated version for the URL. You can use any of the methods covered in this section, and don't use `replace`. Here are the requirements:
|
||||
Complete a função `urlSlug` para que ela converta a string `title` e a retorne sem maiúsculas e com hifens no lugar dos espaços. Você pode usar qualquer método coberto nesta seção, mas não use `replace`. Estes são os requisitos:
|
||||
|
||||
The input is a string with spaces and title-cased words
|
||||
A entrada é uma string com espaços e letras maiúsculas
|
||||
|
||||
The output is a string with the spaces between words replaced by a hyphen (`-`)
|
||||
A saída é uma string cujos espaços foram substituídos por hifens (`-`)
|
||||
|
||||
The output should be all lower-cased letters
|
||||
A saída não deve conter letras maiúsculas
|
||||
|
||||
The output should not have any spaces
|
||||
A saída não deve conter espaços
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should not use the `replace` method for this challenge.
|
||||
Você não pode usar o método `replace` neste desafio.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?replace/g));
|
||||
```
|
||||
|
||||
`urlSlug("Winter Is Coming")` should return the string `winter-is-coming`.
|
||||
`urlSlug("Winter Is Coming")` deve retornar a string `winter-is-coming`.
|
||||
|
||||
```js
|
||||
assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
|
||||
```
|
||||
|
||||
`urlSlug(" Winter Is Coming")` should return the string `winter-is-coming`.
|
||||
`urlSlug(" Winter Is Coming")` deve retornar a string `winter-is-coming`.
|
||||
|
||||
```js
|
||||
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
|
||||
```
|
||||
|
||||
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` should return the string `a-mind-needs-books-like-a-sword-needs-a-whetstone`.
|
||||
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` deve retornar a string `a-mind-needs-books-like-a-sword-needs-a-whetstone`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -55,7 +55,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`urlSlug("Hold The Door")` should return the string `hold-the-door`.
|
||||
`urlSlug("Hold The Door")` deve retornar a string `hold-the-door`.
|
||||
|
||||
```js
|
||||
assert(urlSlug('Hold The Door') === 'hold-the-door');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5e
|
||||
title: Avoid Mutations and Side Effects Using Functional Programming
|
||||
title: Evite Mutações e Efeitos Colaterais usando Programação Funcional
|
||||
challengeType: 1
|
||||
forumTopicId: 301228
|
||||
dashedName: avoid-mutations-and-side-effects-using-functional-programming
|
||||
@ -8,39 +8,39 @@ dashedName: avoid-mutations-and-side-effects-using-functional-programming
|
||||
|
||||
# --description--
|
||||
|
||||
If you haven't already figured it out, the issue in the previous challenge was with the `splice` call in the `tabClose()` function. Unfortunately, `splice` changes the original array it is called on, so the second call to it used a modified array, and gave unexpected results.
|
||||
Caso você ainda não tenha descoberto, o problema do desafio anterior é com a chamada a `splice` na função `tabClose()`. Infelizmente, `splice` modifica o array original no qual opera e, por isso, a segunda chamada usou o array alterado, nos dando resultados inesperados.
|
||||
|
||||
This is a small example of a much larger pattern - you call a function on a variable, array, or an object, and the function changes the variable or something in the object.
|
||||
Este é apenas um pequeno exemplo - você chama uma função e passa uma variável, array ou objeto a ela; a função modifica a variável ou alguma coisa no objeto.
|
||||
|
||||
One of the core principles of functional programming is to not change things. Changes lead to bugs. It's easier to prevent bugs knowing that your functions don't change anything, including the function arguments or any global variable.
|
||||
Um dos principais princípios da programação funcional é que não devemos alterar coisas. Alterações levam a bugs. É mais fácil prever bugs quando se sabe que as funções não mudam nada. Incluindo os seus argumentos e as variáveis globais.
|
||||
|
||||
The previous example didn't have any complicated operations but the `splice` method changed the original array, and resulted in a bug.
|
||||
No exemplo anterior não havia nenhuma operação complicada, mas o método `splice` modificou o array original e o resultado foi um bug.
|
||||
|
||||
Recall that in functional programming, changing or altering things is called <dfn>mutation</dfn>, and the outcome is called a <dfn>side effect</dfn>. A function, ideally, should be a <dfn>pure function</dfn>, meaning that it does not cause any side effects.
|
||||
Lembre-se que, em programação funcional, modificar ou alterar coisas é chamado de <dfn>mutação</dfn> e a consequência é chamada de <dfn>efeito colateral</dfn>. Idealmente, uma função deveria ser uma <dfn>função pura</dfn>, que é uma função que não causa efeitos colaterais.
|
||||
|
||||
Let's try to master this discipline and not alter any variable or object in our code.
|
||||
Vamos tentar dominar esta disciplina e não alterar nenhuma variável ou objeto em nosso código.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fill in the code for the function `incrementer` so it returns the value of the global variable `fixedValue` increased by one.
|
||||
Complete o código da função `incrementer` para que ela retorne o valor da variável global `fixedValue` acrescida em um.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your function `incrementer` should not change the value of `fixedValue` (which is `4`).
|
||||
Sua função `incrementer` não deve alterar o valor de `fixedValue` (que é `4`).
|
||||
|
||||
```js
|
||||
incrementer();
|
||||
assert(fixedValue === 4);
|
||||
```
|
||||
|
||||
Your `incrementer` function should return a value that is one larger than the `fixedValue` value.
|
||||
Sua função `incrementer` deve retornar um valor que é maior que o valor `fixedValue`.
|
||||
|
||||
```js
|
||||
const __newValue = incrementer();
|
||||
assert(__newValue === 5);
|
||||
```
|
||||
|
||||
Your `incrementer` function should return a value based on the global `fixedValue` variable value.
|
||||
Sua função `incrementer` deve retornar um valor baseado no valor da variável global `fixedValue`.
|
||||
|
||||
```js
|
||||
(function () {
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6c
|
||||
title: Combine an Array into a String Using the join Method
|
||||
title: Transforme um Array em uma String Usando o Método join
|
||||
challengeType: 1
|
||||
forumTopicId: 18221
|
||||
dashedName: combine-an-array-into-a-string-using-the-join-method
|
||||
@ -8,47 +8,47 @@ dashedName: combine-an-array-into-a-string-using-the-join-method
|
||||
|
||||
# --description--
|
||||
|
||||
The `join` method is used to join the elements of an array together to create a string. It takes an argument for the delimiter that is used to separate the array elements in the string.
|
||||
O método `join` é usado para juntar os elementos de um array, resultando em uma string. Ele recebe um delimitador como argumento, que é usado para conectar os elementos na string.
|
||||
|
||||
Here's an example:
|
||||
Um exemplo:
|
||||
|
||||
```js
|
||||
var arr = ["Hello", "World"];
|
||||
var str = arr.join(" ");
|
||||
```
|
||||
|
||||
`str` would have a value of the string `Hello World`.
|
||||
O valor de `str` é `Hello World`.
|
||||
# --instructions--
|
||||
|
||||
Use the `join` method (among others) inside the `sentensify` function to make a sentence from the words in the string `str`. The function should return a string. For example, `I-like-Star-Wars` would be converted to `I like Star Wars`. For this challenge, do not use the `replace` method.
|
||||
Use o método `join` (junto com outros) dentro da função `sentensify` para criar uma frase a partir das palavras da string `str`. A função deve retornar uma string. Por exemplo, `I-like-Star-Wars` deve ser convertido para `I like Star Wars`. Não use o método `replace` neste desafio.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `join` method.
|
||||
Você deve usar o método `join`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.join/g));
|
||||
```
|
||||
|
||||
Your code should not use the `replace` method.
|
||||
Você não deve usar o método `replace`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?replace/g));
|
||||
```
|
||||
|
||||
`sentensify("May-the-force-be-with-you")` should return a string.
|
||||
`sentensify("May-the-force-be-with-you")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof sentensify('May-the-force-be-with-you') === 'string');
|
||||
```
|
||||
|
||||
`sentensify("May-the-force-be-with-you")` should return the string `May the force be with you`.
|
||||
`sentensify("May-the-force-be-with-you")` deve retornar a string `May the force be with you`.
|
||||
|
||||
```js
|
||||
assert(sentensify('May-the-force-be-with-you') === 'May the force be with you');
|
||||
```
|
||||
|
||||
`sentensify("The.force.is.strong.with.this.one")` should return the string `The force is strong with this one`.
|
||||
`sentensify("The.force.is.strong.with.this.one")` deve retornar a string `The force is strong with this one`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -57,7 +57,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`sentensify("There,has,been,an,awakening")` should return the string `There has been an awakening`.
|
||||
`sentensify("There,has,been,an,awakening")` deve retornar a string `There has been an awakening`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b66
|
||||
title: Combine Two Arrays Using the concat Method
|
||||
title: Combine Dois Arrays Usando o Método concat
|
||||
challengeType: 1
|
||||
forumTopicId: 301229
|
||||
dashedName: combine-two-arrays-using-the-concat-method
|
||||
@ -8,39 +8,39 @@ dashedName: combine-two-arrays-using-the-concat-method
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Concatenation</dfn> means to join items end to end. JavaScript offers the `concat` method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument to `concat`, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays. Here's an example:
|
||||
<dfn>Concatenação</dfn> significa juntar itens de ponta a ponta. Em JavaScript, ambos strings e arrays possuem o método `concat` e ele funciona igualmente para os dois. Para arrays, o método é chamado em uma instância e um segundo array é passado como argumento. `concat` então junta os dois arrays em um só. O método retorna um novo array e deixa os dois originais intactos. Um exemplo:
|
||||
|
||||
```js
|
||||
[1, 2, 3].concat([4, 5, 6]);
|
||||
```
|
||||
|
||||
The returned array would be `[1, 2, 3, 4, 5, 6]`.
|
||||
`[1, 2, 3, 4, 5, 6]` é o array retornado.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `concat` method in the `nonMutatingConcat` function to concatenate `attach` to the end of `original`. The function should return the concatenated array.
|
||||
Use o método `concat` na função `nonMutatingConcat` para concatenar `attach` ao final de `original`. A função deve retornar o array concatenado.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `concat` method.
|
||||
Você deve usar o método `concat`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.concat/g));
|
||||
```
|
||||
|
||||
The `first` array should not change.
|
||||
O primeiro array, `first`, não deve ser alterado.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
|
||||
```
|
||||
|
||||
The `second` array should not change.
|
||||
O segundo array, `second`, não deve ser alterado.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
|
||||
```
|
||||
|
||||
`nonMutatingConcat([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
|
||||
`nonMutatingConcat([1, 2, 3], [4, 5])` deve retornar `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b62
|
||||
title: Implement map on a Prototype
|
||||
title: Implemente map em um Protótipo
|
||||
challengeType: 1
|
||||
forumTopicId: 301230
|
||||
dashedName: implement-map-on-a-prototype
|
||||
@ -8,25 +8,25 @@ dashedName: implement-map-on-a-prototype
|
||||
|
||||
# --description--
|
||||
|
||||
As you have seen from applying `Array.prototype.map()`, or simply `map()` earlier, the `map` method returns an array of the same length as the one it was called on. It also doesn't alter the original array, as long as its callback function doesn't.
|
||||
Como você viu ao aplicar `Array.prototype.map()`, ou simplesmente `map()` mais cedo, o método `map` retorna um array do mesmo tamanho que o no qual chamamos o método. Ele também não altera o array original desde que a sua função callback não o faça.
|
||||
|
||||
In other words, `map` is a pure function, and its output depends solely on its inputs. Plus, it takes another function as its argument.
|
||||
Em outras palavras, `map` é uma função pura e a sua saída depende somente de suas entradas. Além disso, ele recebe outra função como argumento.
|
||||
|
||||
You might learn a lot about the `map` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`.
|
||||
Você pode aprender muito sobre o método `map` se você implementá-lo por conta própria. Recomenda-se que você use um loop `for` ou o método `Array.prototype.forEach()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write your own `Array.prototype.myMap()`, which should behave exactly like `Array.prototype.map()`. You should not use the built-in `map` method. The `Array` instance can be accessed in the `myMap` method using `this`.
|
||||
Escreva o seu próprio `Array.prototype.myMap()` e faça com que ele se comporte como o `Array.prototype.map()`. Você não deve usar o método `map` disponibilizado. O objeto `Array` pode ser acessado dentro de `myMap` pelo `this`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`new_s` should equal `[46, 130, 196, 10]`.
|
||||
`new_s` deve ser `[46, 130, 196, 10]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]));
|
||||
```
|
||||
|
||||
Your code should not use the `map` method.
|
||||
Você não deve usar o método `map`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?map/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b64
|
||||
title: Implement the filter Method on a Prototype
|
||||
title: Implemente o Método filter em um Protótipo
|
||||
challengeType: 1
|
||||
forumTopicId: 301231
|
||||
dashedName: implement-the-filter-method-on-a-prototype
|
||||
@ -8,21 +8,21 @@ dashedName: implement-the-filter-method-on-a-prototype
|
||||
|
||||
# --description--
|
||||
|
||||
You might learn a lot about the `filter` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`.
|
||||
Você pode aprender muito sobre o método `filter` se você implementá-lo por conta própria. Recomenda-se que você use um loop `for` ou o método `Array.prototype.forEach()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write your own `Array.prototype.myFilter()`, which should behave exactly like `Array.prototype.filter()`. You should not use the built-in `filter` method. The `Array` instance can be accessed in the `myFilter` method using `this`.
|
||||
Escreva o seu próprio `Array.prototype.myFilter()` e faça com que ele se comporte como o `Array.prototype.filter()`. Você não deve usar o método `filter` disponibilizado. O objeto `Array` pode ser acessado dentro de `myFilter` pelo `this`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`new_s` should equal `[23, 65, 5]`.
|
||||
`new_s` deve ser `[23, 65, 5]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]));
|
||||
```
|
||||
|
||||
Your code should not use the `filter` method.
|
||||
Você não deve usar o método `filter`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?filter/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b70
|
||||
title: Introduction to Currying and Partial Application
|
||||
title: Introdução à Aplicação Parcial e Currying
|
||||
challengeType: 1
|
||||
forumTopicId: 301232
|
||||
dashedName: introduction-to-currying-and-partial-application
|
||||
@ -8,11 +8,11 @@ dashedName: introduction-to-currying-and-partial-application
|
||||
|
||||
# --description--
|
||||
|
||||
The <dfn>arity</dfn> of a function is the number of arguments it requires. <dfn>Currying</dfn> a function means to convert a function of N arity into N functions of arity 1.
|
||||
A <dfn>aridade</dfn> de uma função é o número de argumentos que ela toma. Realizar <dfn>currying</dfn> em uma função significa transformar uma função de aridade N em N funções de aridade 1.
|
||||
|
||||
In other words, it restructures a function so it takes one argument, then returns another function that takes the next argument, and so on.
|
||||
Em outras palavras, a função é reestruturada para que ela receba apenas um argumento e retorne outra função que recebe o próximo argumento e assim por diante.
|
||||
|
||||
Here's an example:
|
||||
Um exemplo:
|
||||
|
||||
```js
|
||||
function unCurried(x, y) {
|
||||
@ -30,16 +30,16 @@ const curried = x => y => x + y
|
||||
curried(1)(2)
|
||||
```
|
||||
|
||||
`curried(1)(2)` would return `3`.
|
||||
`curried(1)(2)` retornaria `3`.
|
||||
|
||||
This is useful in your program if you can't supply all the arguments to a function at one time. You can save each function call into a variable, which will hold the returned function reference that takes the next argument when it's available. Here's an example using the curried function in the example above:
|
||||
Isso é útil em seu programa quando você não pode fornecer todos os argumentos para uma função de uma só vez. Você pode salvar cada chamada de função em uma variável, que será uma referência à função retornada que recebe o próximo argumento quando ele estiver disponível. Um exemplo usando a função do exemplo acima:
|
||||
|
||||
```js
|
||||
var funcForY = curried(1);
|
||||
console.log(funcForY(2)); // 3
|
||||
```
|
||||
|
||||
Similarly, <dfn>partial application</dfn> can be described as applying a few arguments to a function at a time and returning another function that is applied to more arguments. Here's an example:
|
||||
Da mesma forma, <dfn>aplicação parcial</dfn> pode ser descrita como a aplicação de alguns argumentos a uma função e o retorno de outra função à qual é aplicada a mais argumentos. Um exemplo:
|
||||
|
||||
```js
|
||||
function impartial(x, y, z) {
|
||||
@ -51,29 +51,29 @@ partialFn(10); // 13
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fill in the body of the `add` function so it uses currying to add parameters `x`, `y`, and `z`.
|
||||
Complete a função `add` de forma que ela use currying para adicionar os parâmetros `x`, `y` e `z`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`add(10)(20)(30)` should return `60`.
|
||||
`add(10)(20)(30)` deve retornar `60`.
|
||||
|
||||
```js
|
||||
assert(add(10)(20)(30) === 60);
|
||||
```
|
||||
|
||||
`add(1)(2)(3)` should return `6`.
|
||||
`add(1)(2)(3)` deve retornar `6`.
|
||||
|
||||
```js
|
||||
assert(add(1)(2)(3) === 6);
|
||||
```
|
||||
|
||||
`add(11)(22)(33)` should return `66`.
|
||||
`add(11)(22)(33)` deve retornar `66`.
|
||||
|
||||
```js
|
||||
assert(add(11)(22)(33) === 66);
|
||||
```
|
||||
|
||||
Your code should include a final statement that returns `x + y + z`.
|
||||
Em seu código deve haver uma instrução final que retorna `x + y + z`.
|
||||
|
||||
```js
|
||||
assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8d367417b2b2512b5b
|
||||
title: Learn About Functional Programming
|
||||
title: Aprenda Sobre Programação Funcional
|
||||
challengeType: 1
|
||||
forumTopicId: 301233
|
||||
dashedName: learn-about-functional-programming
|
||||
@ -8,31 +8,31 @@ dashedName: learn-about-functional-programming
|
||||
|
||||
# --description--
|
||||
|
||||
Functional programming is a style of programming where solutions are simple, isolated functions, without any side effects outside of the function scope: `INPUT -> PROCESS -> OUTPUT`
|
||||
Programação funcional é um estilo de programação em que as soluções são funções simples, isoladas e livres de efeitos colaterais fora do escopo da função: `ENTRADA -> PROCESSAMENTO -> SAÍDA`
|
||||
|
||||
Functional programming is about:
|
||||
Quando falamos de programação funcional, pensamos em:
|
||||
|
||||
1) Isolated functions - there is no dependence on the state of the program, which includes global variables that are subject to change
|
||||
1) Funções isoladas: nenhuma função depende do estado do programa, incluindo variáveis globais, que podem sofrer mudanças
|
||||
|
||||
2) Pure functions - the same input always gives the same output
|
||||
2) Funções puras: a mesma entrada sempre devolve a mesma saída
|
||||
|
||||
3) Functions with limited side effects - any changes, or mutations, to the state of the program outside the function are carefully controlled
|
||||
3) Funções com efeitos colaterais limitados: qualquer alteração ou mutação do estado do programa fora da função é cuidadosamente controlada
|
||||
|
||||
# --instructions--
|
||||
|
||||
The members of freeCodeCamp happen to love tea.
|
||||
Os membros do freeCodeCamp adoram chá.
|
||||
|
||||
In the code editor, the `prepareTea` and `getTea` functions are already defined for you. Call the `getTea` function to get 40 cups of tea for the team, and store them in the `tea4TeamFCC` variable.
|
||||
As funções `prepareTea` e `getTea` já estão definidas para você no editor de texto. Chame a função `getTea` para adquirir 40 xícaras de chá para o time e as armazene na variável `tea4TeamFCC`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `tea4TeamFCC` variable should hold 40 cups of tea for the team.
|
||||
A variável `tea4TeamFCC` deve conter 40 xícaras de chá para o time.
|
||||
|
||||
```js
|
||||
assert(tea4TeamFCC.length === 40);
|
||||
```
|
||||
|
||||
The `tea4TeamFCC` variable should hold cups of green tea.
|
||||
A variável `tea4TeamFCC` deve conter xícaras de chá verde.
|
||||
|
||||
```js
|
||||
assert(tea4TeamFCC[0] === 'greenTea');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5f
|
||||
title: Pass Arguments to Avoid External Dependence in a Function
|
||||
title: Passe Argumentos para Evitar Dependências Externas em Funções
|
||||
challengeType: 1
|
||||
forumTopicId: 301234
|
||||
dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
|
||||
@ -8,39 +8,39 @@ dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge was a step closer to functional programming principles, but there is still something missing.
|
||||
No último desafio você deu um passo a mais nos princípios de programação funcional, mas ainda falta algo.
|
||||
|
||||
We didn't alter the global variable value, but the function `incrementer` would not work without the global variable `fixedValue` being there.
|
||||
Nós não mudamos o valor dela, mas a função `incrementer` não funciona sem a variável global `fixedValue`.
|
||||
|
||||
Another principle of functional programming is to always declare your dependencies explicitly. This means if a function depends on a variable or object being present, then pass that variable or object directly into the function as an argument.
|
||||
Outro princípio da programação funcional é que sempre devemos declarar nossas dependências explicitamente. Isso significa que, se uma função depende de uma variável ou objeto, então devemos passar esta variável ou objeto diretamente como argumento a ela.
|
||||
|
||||
There are several good consequences from this principle. The function is easier to test, you know exactly what input it takes, and it won't depend on anything else in your program.
|
||||
Há muitas boas consequências nesse princípio: a função se torna mais fácil de testar, você sabe exatamente quais são as suas entradas e ela não depende de mais nada no seu programa.
|
||||
|
||||
This can give you more confidence when you alter, remove, or add new code. You would know what you can or cannot change and you can see where the potential traps are.
|
||||
Isso faz com que você tenha mais confiança ao alterar, remover ou adicionar código, pois sabe o que pode ou não pode alterar e identifica armadilhas em potencial com mais facilidade.
|
||||
|
||||
Finally, the function would always produce the same output for the same set of inputs, no matter what part of the code executes it.
|
||||
Finalmente, a função sempre produzirá a mesma saída para o mesmo conjunto de entradas, não importa de onde no código ela é chamada.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Let's update the `incrementer` function to clearly declare its dependencies.
|
||||
Vamos atualizar a função `incrementer` e declarar explicitamente as suas dependências.
|
||||
|
||||
Write the `incrementer` function so it takes an argument, and then returns a result after increasing the value by one.
|
||||
Escreva a função `incrementer` de forma que ela receba um argumento e retorne o valor incrementado em um.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your function `incrementer` should not change the value of `fixedValue` (which is `4`).
|
||||
A função `incrementer` não deve alterar o valor de `fixedValue`, que é `4`.
|
||||
|
||||
```js
|
||||
assert(fixedValue === 4);
|
||||
```
|
||||
|
||||
Your `incrementer` function should take an argument.
|
||||
A função `incrementer` deve receber um argumento.
|
||||
|
||||
```js
|
||||
assert(incrementer.length === 1);
|
||||
```
|
||||
|
||||
Your `incrementer` function should return a value that is one larger than the `fixedValue` value.
|
||||
Sua função `incrementer` deve retornar um valor que é maior que o valor `fixedValue`.
|
||||
|
||||
```js
|
||||
const __newValue = incrementer(fixedValue);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b60
|
||||
title: Refactor Global Variables Out of Functions
|
||||
title: Refatore Funções Para Que Não Usem Variáveis Globais
|
||||
challengeType: 1
|
||||
forumTopicId: 301235
|
||||
dashedName: refactor-global-variables-out-of-functions
|
||||
@ -8,23 +8,23 @@ dashedName: refactor-global-variables-out-of-functions
|
||||
|
||||
# --description--
|
||||
|
||||
So far, we have seen two distinct principles for functional programming:
|
||||
Até agora vimos dois princípios diferentes de programação funcional:
|
||||
|
||||
1) Don't alter a variable or object - create new variables and objects and return them if need be from a function. Hint: using something like `var newArr = arrVar`, where `arrVar` is an array will simply create a reference to the existing variable and not a copy. So changing a value in `newArr` would change the value in `arrVar`.
|
||||
1) Não altere variáveis ou objetos: crie novas variáveis ou objetos e os retorne, caso necessário, de uma função. Dica: escrever algo como `var newArr = arrVar` onde `arrVar` é um array não o copiará para a nova a variável, e sim apenas criará uma nova referência ao mesmo objeto. Então mudar um valor em `newArr` também o muda em `arrVar`.
|
||||
|
||||
2) Declare function parameters - any computation inside a function depends only on the arguments passed to the function, and not on any global object or variable.
|
||||
2) Declare parâmetros de funções: qualquer computação dentro de uma função depende apenas dos argumentos passados a ela; nunca de uma variável ou objeto global.
|
||||
|
||||
Adding one to a number is not very exciting, but we can apply these principles when working with arrays or more complex objects.
|
||||
Incrementar um número em um não é tão divertido, mas podemos aplicar esses princípios ao trabalhar com arrays ou objetos mais complexos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Rewrite the code so the global array `bookList` is not changed inside either function. The `add` function should add the given `bookName` to the end of the array passed to it and return a new array (list). The `remove` function should remove the given `bookName` from the array passed to it.
|
||||
Reescreva o código de forma que o array global `bookList` não seja alterado em nenhuma das funções. A função `add` deve adicionar o nome do livro, `bookName` ao array passado e retornar um novo array. A função `remove` deve remover o `bookName` do array passado a ela.
|
||||
|
||||
**Note:** Both functions should return an array, and any new parameters should be added before the `bookName` parameter.
|
||||
**Obs:** Ambas as funções devem retornar um array e novos parâmetros devem ser adicionados antes do parâmetro `bookName`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`bookList` should not change and still equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
|
||||
`bookList` não deve ser alterado e precisa permanecer igual a `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`newBookList` should equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
|
||||
`newBookList` deve ser igual a `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -53,7 +53,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`newerBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
|
||||
`newerBookList` deve ser igual a `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -66,7 +66,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`newestBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
|
||||
`newestBookList` deve ser igual a `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 9d7123c8c441eeafaeb5bdef
|
||||
title: Remove Elements from an Array Using slice Instead of splice
|
||||
title: Remova Elementos de um Array Usando slice em vez de splice
|
||||
challengeType: 1
|
||||
forumTopicId: 301236
|
||||
dashedName: remove-elements-from-an-array-using-slice-instead-of-splice
|
||||
@ -8,38 +8,38 @@ dashedName: remove-elements-from-an-array-using-slice-instead-of-splice
|
||||
|
||||
# --description--
|
||||
|
||||
A common pattern while working with arrays is when you want to remove items and keep the rest of the array. JavaScript offers the `splice` method for this, which takes arguments for the index of where to start removing items, then the number of items to remove. If the second argument is not provided, the default is to remove items through the end. However, the `splice` method mutates the original array it is called on. Here's an example:
|
||||
É comum precisar remover alguns itens de um array e manter o resto. O JavaScript oferece o método `splice`, que recebe uma posição de onde começar a remover e o número de elementos para remover como argumentos para isso. Se o segundo argumento for omitido, o padrão é remover todos os itens até o final. No entanto, o método `splice` modifica o array original em que é chamado. Um exemplo:
|
||||
|
||||
```js
|
||||
var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
cities.splice(3, 1);
|
||||
```
|
||||
|
||||
Here `splice` returns the string `London` and deletes it from the cities array. `cities` will have the value `["Chicago", "Delhi", "Islamabad", "Berlin"]`.
|
||||
Aqui `splice` retorna a string `London` e a remove do array cities. `cities` terá o valor `["Chicago", "Delhi", "Islamabad", "Berlin"]`.
|
||||
|
||||
As we saw in the last challenge, the `slice` method does not mutate the original array, but returns a new one which can be saved into a variable. Recall that the `slice` method takes two arguments for the indices to begin and end the slice (the end is non-inclusive), and returns those items in a new array. Using the `slice` method instead of `splice` helps to avoid any array-mutating side effects.
|
||||
Como vimos no último desafio, o método `slice` não altera o array original; ele retorna um novo array que pode ser armazenado em uma variável. Lembre-se que o método `slice` toma dois argumentos para os índices de início e fim e retorna um array com os elementos presentes entre esses índices (o índice de fim é não-inclusivo). Usar o método `slice` em vez do `splice` ajuda a evitar alterações em arrays e, portanto, efeitos colaterais.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Rewrite the function `nonMutatingSplice` by using `slice` instead of `splice`. It should limit the provided `cities` array to a length of 3, and return a new array with only the first three items.
|
||||
Reescreva a função `nonMutatingSplice` com `slice` em vez de `splice`. Ela deve limitar o array `cities` providenciado ao tamanho 3 e retornar um novo array com apenas os três primeiros itens.
|
||||
|
||||
Do not mutate the original array provided to the function.
|
||||
Não modifique o array original passado à função.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `slice` method.
|
||||
Você deve usar o método `slice`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.slice/g));
|
||||
```
|
||||
|
||||
Your code should not use the `splice` method.
|
||||
Você não deve usar o método `splice`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?splice/g));
|
||||
```
|
||||
|
||||
The `inputCities` array should not change.
|
||||
O array `inputCities` não deve ser alterado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` should return `["Chicago", "Delhi", "Islamabad"]`.
|
||||
`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` deve retornar `["Chicago", "Delhi", "Islamabad"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b6a
|
||||
title: Return a Sorted Array Without Changing the Original Array
|
||||
title: Retorne um Array Ordenado Sem Modificar o Array Original
|
||||
challengeType: 1
|
||||
forumTopicId: 301237
|
||||
dashedName: return-a-sorted-array-without-changing-the-original-array
|
||||
@ -8,27 +8,27 @@ dashedName: return-a-sorted-array-without-changing-the-original-array
|
||||
|
||||
# --description--
|
||||
|
||||
A side effect of the `sort` method is that it changes the order of the elements in the original array. In other words, it mutates the array in place. One way to avoid this is to first concatenate an empty array to the one being sorted (remember that `slice` and `concat` return a new array), then run the `sort` method.
|
||||
Um efeito colateral do método `sort` é que ele altera a ordem dos elementos no array original. Em outras palavras, o array sofre uma mutação. Uma forma de evitar isto é primeiro concatenar um array vazio ao array a ordenar (não esqueça que `slice` e `concat` retornam um novo array) e, então, executar o método `sort` no novo array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `sort` method in the `nonMutatingSort` function to sort the elements of an array in ascending order. The function should return a new array, and not mutate the `globalArray` variable.
|
||||
Use o método `sort`na função `nonMutatingSort` para ordenar os elementos de um array em ordem crescente. A função deve retornar um novo array sem alterar a variável `globalArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `sort` method.
|
||||
Você deve usar o método `sort`.
|
||||
|
||||
```js
|
||||
assert(nonMutatingSort.toString().match(/\.sort/g));
|
||||
```
|
||||
|
||||
The `globalArray` variable should not change.
|
||||
A variável `globalArray` não deve ser alterada.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
|
||||
```
|
||||
|
||||
`nonMutatingSort(globalArray)` should return `[2, 3, 5, 6, 9]`.
|
||||
`nonMutatingSort(globalArray)` deve retornar `[2, 3, 5, 6, 9]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -37,26 +37,26 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`nonMutatingSort(globalArray)` should not be hard coded.
|
||||
`nonMutatingSort(globalArray)` não deve conter um array prontamente ordenado.
|
||||
|
||||
```js
|
||||
assert(!nonMutatingSort.toString().match(/\[.*?[23569].*?\]/gs));
|
||||
```
|
||||
|
||||
The function should return a new array, not the array passed to it.
|
||||
A função deve retornar um novo array, não o array passado a ela.
|
||||
|
||||
```js
|
||||
assert(nonMutatingSort(globalArray) !== globalArray);
|
||||
```
|
||||
|
||||
`nonMutatingSort([1, 30, 4, 21, 100000])` should return `[1, 4, 21, 30, 100000]`.
|
||||
`nonMutatingSort([1, 30, 4, 21, 100000])` deve retornar `[1, 4, 21, 30, 100000]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(nonMutatingSort([1, 30, 4, 21, 100000])) ===
|
||||
JSON.stringify([1, 4, 21, 30, 100000]))
|
||||
```
|
||||
|
||||
`nonMutatingSort([140000, 104, 99])` should return `[99, 104, 140000]`.
|
||||
`nonMutatingSort([140000, 104, 99])` deve retornar `[99, 104, 140000]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(nonMutatingSort([140000, 104, 99])) ===
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b90367417b2b2512b65
|
||||
title: Return Part of an Array Using the slice Method
|
||||
title: Retorne Parte de um Array Usando o Método slice
|
||||
challengeType: 1
|
||||
forumTopicId: 301239
|
||||
dashedName: return-part-of-an-array-using-the-slice-method
|
||||
@ -8,30 +8,30 @@ dashedName: return-part-of-an-array-using-the-slice-method
|
||||
|
||||
# --description--
|
||||
|
||||
The `slice` method returns a copy of certain elements of an array. It can take two arguments, the first gives the index of where to begin the slice, the second is the index for where to end the slice (and it's non-inclusive). If the arguments are not provided, the default is to start at the beginning of the array through the end, which is an easy way to make a copy of the entire array. The `slice` method does not mutate the original array, but returns a new one.
|
||||
O método `slice` retorna uma fatia de elementos de um array. Ele pode receber dois argumentos, sendo o primeiro o índice de onde começar a fatiar e o segundo de onde terminar. O índice de fim não é inclusivo. Se os argumentos não forem providenciados, o padrão é começar pelo início e terminar no fim, ou seja, é uma forma simples de criar uma cópia do array inteiro. O método `slice` retorna um novo array sem modificar o original.
|
||||
|
||||
Here's an example:
|
||||
Um exemplo:
|
||||
|
||||
```js
|
||||
var arr = ["Cat", "Dog", "Tiger", "Zebra"];
|
||||
var newArray = arr.slice(1, 3);
|
||||
```
|
||||
|
||||
`newArray` would have the value `["Dog", "Tiger"]`.
|
||||
`newArray` terá o valor `["Dog", "Tiger"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `slice` method in the `sliceArray` function to return part of the `anim` array given the provided `beginSlice` and `endSlice` indices. The function should return an array.
|
||||
Use o método `slice` na função `sliceArray` para retornar parte do array `anim` dado os índices `beginSlice` e `endSlice` providenciados. A função deve retornar um array.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `slice` method.
|
||||
Você deve usar o método `slice`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.slice/g));
|
||||
```
|
||||
|
||||
The `inputAnim` variable should not change.
|
||||
A variável `inputAnim` não deve ser alterada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -40,7 +40,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` should return `["Dog", "Tiger"]`.
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` deve retornar `["Dog", "Tiger"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -49,7 +49,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` should return `["Cat"]`.
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` deve retornar `["Cat"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -58,7 +58,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` should return `["Dog", "Tiger", "Zebra"]`.
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` deve retornar `["Dog", "Tiger", "Zebra"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b69
|
||||
title: Sort an Array Alphabetically using the sort Method
|
||||
title: Ordene um Array Alfabeticamente Usando o Método sort
|
||||
challengeType: 1
|
||||
forumTopicId: 18303
|
||||
dashedName: sort-an-array-alphabetically-using-the-sort-method
|
||||
@ -8,9 +8,9 @@ dashedName: sort-an-array-alphabetically-using-the-sort-method
|
||||
|
||||
# --description--
|
||||
|
||||
The `sort` method sorts the elements of an array according to the callback function.
|
||||
O método `sort` consegue ordenar os elementos de um array de acordo com uma função callback.
|
||||
|
||||
For example:
|
||||
Por exemplo:
|
||||
|
||||
```js
|
||||
function ascendingOrder(arr) {
|
||||
@ -21,7 +21,7 @@ function ascendingOrder(arr) {
|
||||
ascendingOrder([1, 5, 2, 3, 4]);
|
||||
```
|
||||
|
||||
This would return the value `[1, 2, 3, 4, 5]`.
|
||||
O código acima retorna `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
function reverseAlpha(arr) {
|
||||
@ -32,23 +32,23 @@ function reverseAlpha(arr) {
|
||||
reverseAlpha(['l', 'h', 'z', 'b', 's']);
|
||||
```
|
||||
|
||||
This would return the value `['z', 's', 'l', 'h', 'b']`.
|
||||
Este retorna o valor `['z', 's', 'l', 'h', 'b']`.
|
||||
|
||||
JavaScript's default sorting method is by string Unicode point value, which may return unexpected results. Therefore, it is encouraged to provide a callback function to specify how to sort the array items. When such a callback function, normally called `compareFunction`, is supplied, the array elements are sorted according to the return value of the `compareFunction`: If `compareFunction(a,b)` returns a value less than 0 for two elements `a` and `b`, then `a` will come before `b`. If `compareFunction(a,b)` returns a value greater than 0 for two elements `a` and `b`, then `b` will come before `a`. If `compareFunction(a,b)` returns a value equal to 0 for two elements `a` and `b`, then `a` and `b` will remain unchanged.
|
||||
O método de ordenação padrão do JavaScript é por valores de ponto Unicode, o que pode nos dar resultados inesperados. Por isso você é encorajado a providenciar uma função callback para especificar como a ordenação deve ocorrer. Quando tal função callback (comumente chamada de `compareFunction`, ou função de comparação) é providenciada, os elementos do array são ordenados de acordo com o valor de retorno dela: se `compareFunction(a,b)` retornar um valor menor que 0 para dois elementos `a` e `b`, então `a` virá antes de `b`. Se `compareFunction(a,b)` retornar um valor maior que 0 para dois elementos `a` e `b`, então `b` virá antes de `a`. Finalmente, se `compareFunction(a,b)` retornar 0, então `a` e `b` não trocarão de lugar entre si.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `sort` method in the `alphabeticalOrder` function to sort the elements of `arr` in alphabetical order.
|
||||
Use o método `sort` na função `alphabeticalOrder` para ordenar os elementos de `arr` em ordem alfabética.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `sort` method.
|
||||
Você deve usar o método `sort`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.sort/g));
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` should return `["a", "a", "c", "d", "g", "z"]`.
|
||||
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` deve retornar `["a", "a", "c", "d", "g", "z"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -57,7 +57,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` should return `["a", "h", "m", "m", "n", "x"]`.
|
||||
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` deve retornar `["a", "h", "m", "m", "n", "x"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -66,7 +66,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` should return `["a", "a", "a", "a", "t", "x"]`.
|
||||
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` deve retornar `["a", "a", "a", "a", "t", "x"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6b
|
||||
title: Split a String into an Array Using the split Method
|
||||
title: Divida uma String em um Array Usando o Método split
|
||||
challengeType: 1
|
||||
forumTopicId: 18305
|
||||
dashedName: split-a-string-into-an-array-using-the-split-method
|
||||
@ -8,9 +8,9 @@ dashedName: split-a-string-into-an-array-using-the-split-method
|
||||
|
||||
# --description--
|
||||
|
||||
The `split` method splits a string into an array of strings. It takes an argument for the delimiter, which can be a character to use to break up the string or a regular expression. For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string.
|
||||
O método `split` divide uma string em um array de strings. Ela recebe um delimitador, que pode ser um caractere ou uma expressão regular, como argumento para dividir a string. Por exemplo, se o delimitador for um espaço, você recebe um array de palavras. Se o delimitador for a string vazia, você recebe um array contendo os caracteres da string.
|
||||
|
||||
Here are two examples that split one string by spaces, then another by digits using a regular expression:
|
||||
Abaixo há dois exemplos de uso de split, um separando uma string por espaços, e outro por dígitos usando uma expressão regular:
|
||||
|
||||
```js
|
||||
var str = "Hello World";
|
||||
@ -20,23 +20,23 @@ var otherString = "How9are7you2today";
|
||||
var byDigits = otherString.split(/\d/);
|
||||
```
|
||||
|
||||
`bySpace` would have the value `["Hello", "World"]` and `byDigits` would have the value `["How", "are", "you", "today"]`.
|
||||
`bySpace` terá o valor `["Hello", "World"]` e `byDigits` terá o valor `["How", "are", "you", "today"]`.
|
||||
|
||||
Since strings are immutable, the `split` method makes it easier to work with them.
|
||||
Como strings são imutáveis, o método `split` facilita o trabalho com elas.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `split` method inside the `splitify` function to split `str` into an array of words. The function should return the array. Note that the words are not always separated by spaces, and the array should not contain punctuation.
|
||||
Use o método `split` na função `splitify` para dividir `str` em um array de palavras. A função deve retornar o array. Note que as palavras nem sempre são separadas por espaços; o array não deve conter nenhuma pontuação.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `split` method.
|
||||
Você deve usar o método `split`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.split/g));
|
||||
```
|
||||
|
||||
`splitify("Hello World,I-am code")` should return `["Hello", "World", "I", "am", "code"]`.
|
||||
`splitify("Hello World,I-am code")` deve retornar `["Hello", "World", "I", "am", "code"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -45,7 +45,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`splitify("Earth-is-our home")` should return `["Earth", "is", "our", "home"]`.
|
||||
`splitify("Earth-is-our home")` deve retornar `["Earth", "is", "our", "home"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -54,7 +54,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`splitify("This.is.a-sentence")` should return `["This", "is", "a", "sentence"]`.
|
||||
`splitify("This.is.a-sentence")` deve retornar `["This", "is", "a", "sentence"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5c
|
||||
title: Understand Functional Programming Terminology
|
||||
title: Entenda a Terminologia de Programação Funcional
|
||||
challengeType: 1
|
||||
forumTopicId: 301240
|
||||
dashedName: understand-functional-programming-terminology
|
||||
@ -8,47 +8,47 @@ dashedName: understand-functional-programming-terminology
|
||||
|
||||
# --description--
|
||||
|
||||
The FCC Team had a mood swing and now wants two types of tea: green tea and black tea. General Fact: Client mood swings are pretty common.
|
||||
Houve uma mudança de humor no time da FCC e os membros agora querem dois tipos de chá: verde e preto. Fato: clientes sofrem mudanças de humor e de opinião frequentemente.
|
||||
|
||||
With that information, we'll need to revisit the `getTea` function from last challenge to handle various tea requests. We can modify `getTea` to accept a function as a parameter to be able to change the type of tea it prepares. This makes `getTea` more flexible, and gives the programmer more control when client requests change.
|
||||
Por causa disso, precisaremos rever a função `getTea` do último desafio para lidar com vários pedidos de chá. Podemos modificar a `getTea` para aceitar uma função como argumento e torná-la capaz de preparar outros tipos de chá. Isso faz com que `getTea` seja mais flexível e dá mais controle ao programador quando os requisitos do cliente mudam.
|
||||
|
||||
But first, let's cover some functional terminology:
|
||||
Mas primeiro, vejamos um pouco de terminologia funcional:
|
||||
|
||||
<dfn>Callbacks</dfn> are the functions that are slipped or passed into another function to decide the invocation of that function. You may have seen them passed to other methods, for example in `filter`, the callback function tells JavaScript the criteria for how to filter an array.
|
||||
<dfn>Callbacks</dfn> são funções que são passadas a outras funções, que decidem quando e como são chamados. Você pode ter visto alguns sendo passados a outros métodos. Em `filter`, por exemplo, o callback diz ao JavaScript qual é o critério para filtrar um array.
|
||||
|
||||
Functions that can be assigned to a variable, passed into another function, or returned from another function just like any other normal value, are called <dfn>first class</dfn> functions. In JavaScript, all functions are first class functions.
|
||||
Funções que podem ser atribuídas a variáveis, passadas a outras funções ou retornadas de outra função como qualquer outro valor são chamadas de <dfn>funções de primeira classe</dfn>. Em JavaScript, todas as funções são funções de primeira classe.
|
||||
|
||||
The functions that take a function as an argument, or return a function as a return value are called <dfn>higher order</dfn> functions.
|
||||
As funções que recebem funções como argumentos ou retornam outras funções como valores são chamadas de <dfn>funções de ordem superior</dfn>.
|
||||
|
||||
When functions are passed in to or returned from another function, then those functions which were passed in or returned can be called a <dfn>lambda</dfn>.
|
||||
Funções podem ser chamadas de <dfn>lambda</dfn> quando passadas para outra função ou retornadas a partir dela.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Prepare 27 cups of green tea and 13 cups of black tea and store them in `tea4GreenTeamFCC` and `tea4BlackTeamFCC` variables, respectively. Note that the `getTea` function has been modified so it now takes a function as the first argument.
|
||||
Prepare 27 xícaras de chá verde e 13 xícaras de chá preto; armazene-as nas variáveis `tea4GreenTeamFCC` e `tea4BlackTeamFCC`, respectivamente. Perceba que a função `getTea` foi alterada para receber uma função como primeiro argumento.
|
||||
|
||||
Note: The data (the number of cups of tea) is supplied as the last argument. We'll discuss this more in later lessons.
|
||||
Obs: O número de xícaras de chá se tornou o último parâmetro da função. Discutiremos mais sobre isso nas próximas aulas.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `tea4GreenTeamFCC` variable should hold 27 cups of green tea for the team.
|
||||
A variável `tea4GreenTeamFCC` deve conter 27 xícaras de chá verde para o time.
|
||||
|
||||
```js
|
||||
assert(tea4GreenTeamFCC.length === 27);
|
||||
```
|
||||
|
||||
The `tea4GreenTeamFCC` variable should hold cups of green tea.
|
||||
A variável `tea4GreenTeamFCC` deve conter xícaras de chá verde.
|
||||
|
||||
```js
|
||||
assert(tea4GreenTeamFCC[0] === 'greenTea');
|
||||
```
|
||||
|
||||
The `tea4BlackTeamFCC` variable should hold 13 cups of black tea.
|
||||
A variável `tea4BlackTeamFCC` deve conter 13 xícaras de chá preto.
|
||||
|
||||
```js
|
||||
assert(tea4BlackTeamFCC.length === 13);
|
||||
```
|
||||
|
||||
The `tea4BlackTeamFCC` variable should hold cups of black tea.
|
||||
A variável `tea4BlackTeamFCC` deve conter xícaras de chá preto.
|
||||
|
||||
```js
|
||||
assert(tea4BlackTeamFCC[0] === 'blackTea');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5d
|
||||
title: Understand the Hazards of Using Imperative Code
|
||||
title: Entenda os Perigos da Programação Imperativa
|
||||
challengeType: 1
|
||||
forumTopicId: 301241
|
||||
dashedName: understand-the-hazards-of-using-imperative-code
|
||||
@ -8,31 +8,31 @@ dashedName: understand-the-hazards-of-using-imperative-code
|
||||
|
||||
# --description--
|
||||
|
||||
Functional programming is a good habit. It keeps your code easy to manage, and saves you from sneaky bugs. But before we get there, let's look at an imperative approach to programming to highlight where you may have issues.
|
||||
Usar programação funcional é um bom hábito. Faz com que o seu código seja fácil de manter e o livra de bugs sorrateiros. Mas antes de fazer a transição, vamos rever uma abordagem imperativa para destacar onde pode haver problemas.
|
||||
|
||||
In English (and many other languages), the imperative tense is used to give commands. Similarly, an imperative style in programming is one that gives the computer a set of statements to perform a task.
|
||||
Em português (e vários outros idiomas), o modo verbal imperativo é usado para dar ordens. Da mesma forma, o estilo imperativo em programação é um estilo que dá um conjunto de instruções para um computador realizar uma tarefa.
|
||||
|
||||
Often the statements change the state of the program, like updating global variables. A classic example is writing a `for` loop that gives exact directions to iterate over the indices of an array.
|
||||
Essas instruções frequentemente alteram o estado do programa ao atualizar variáveis globais, por exemplo. Um exemplo clássico é escrever um loop `for`, que é explícito ao dar direções para percorrer um array.
|
||||
|
||||
In contrast, functional programming is a form of declarative programming. You tell the computer what you want done by calling a method or function.
|
||||
Em contrapartida, a programação funcional é uma forma de programação declarativa. Você diz ao computador o que quer fazer chamando um método ou função.
|
||||
|
||||
JavaScript offers many predefined methods that handle common tasks so you don't need to write out how the computer should perform them. For example, instead of using the `for` loop mentioned above, you could call the `map` method which handles the details of iterating over an array. This helps to avoid semantic errors, like the "Off By One Errors" that were covered in the Debugging section.
|
||||
O JavaScript oferece muitos métodos predefinidos que lidam com tarefas comuns, então você não precisa escrever como o computador deve executá-las. Por exemplo, em vez de usar um loop `for`, você pode chamar o método `map`, que lida com os detalhes de como percorrer um array. Isso ajuda a evitar erros semânticos, como o "Off By One", que foram cobertos na seção de depuração.
|
||||
|
||||
Consider the scenario: you are browsing the web in your browser, and want to track the tabs you have opened. Let's try to model this using some simple object-oriented code.
|
||||
Considere o cenário: você está navegando na web com o seu navegador e quer rastrear as abas que você abriu. Vamos tentar modelar isso usando orientação a objetos de forma simples.
|
||||
|
||||
A Window object is made up of tabs, and you usually have more than one Window open. The titles of each open site in each Window object is held in an array. After working in the browser (opening new tabs, merging windows, and closing tabs), you want to print the tabs that are still open. Closed tabs are removed from the array and new tabs (for simplicity) get added to the end of it.
|
||||
Um objeto Window (Janela) é composto de abas e normalmente há mais de uma janela aberta. Os títulos de cada site aberto em cada objeto Window é armazenado em um array. Depois de usar o navegador (abrindo novas abas, juntando janelas, fechando abas), você quer imprimir as abas que ainda estão abertas. Abas fechadas são removidas do array e novas abas são adicionadas ao fim dele (por simplicidade).
|
||||
|
||||
The code editor shows an implementation of this functionality with functions for `tabOpen()`, `tabClose()`, and `join()`. The array `tabs` is part of the Window object that stores the name of the open pages.
|
||||
No editor de texto há uma implementação dessa funcionalidade com as funções `tabOpen()`, `tabClose()` e `join()`. O array `tabs` é um atributo do objeto Window e armazena o nome das páginas abertas.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Examine the code in the editor. It's using a method that has side effects in the program, causing incorrect behaviour. The final list of open tabs, stored in `finalTabs.tabs`, should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` but the list produced by the code is slightly different.
|
||||
Examine o código no editor. Nele é usado um método que possui efeitos colaterais no programa e causa comportamento incorreto. A lista final de abas abertas armazenada em `finalTabs.tabs` deveria ser `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` mas a lista produzida pelo código é ligeiramente diferente.
|
||||
|
||||
Change `Window.prototype.tabClose` so that it removes the correct tab.
|
||||
Modifique `Window.prototype.tabClose` de forma que ele remova a aba correta.
|
||||
|
||||
# --hints--
|
||||
|
||||
`finalTabs.tabs` should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
|
||||
`finalTabs.tabs` deve ser `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
|
||||
|
||||
```js
|
||||
assert.deepEqual(finalTabs.tabs, [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b88367417b2b2512b45
|
||||
title: 'Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem'
|
||||
title: 'Use as Funções de Ordem Superior map, filter ou reduce para Solucionar um Problema Complexo'
|
||||
challengeType: 1
|
||||
forumTopicId: 301311
|
||||
dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem
|
||||
@ -8,30 +8,30 @@ dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-p
|
||||
|
||||
# --description--
|
||||
|
||||
Now that you have worked through a few challenges using higher-order functions like `map()`, `filter()`, and `reduce()`, you now get to apply them to solve a more complex challenge.
|
||||
Agora que você já realizou alguns desafios usando funções de ordem superior como `map()`, `filter()` e `reduce()`, você pode usá-las para resolver um desafio mais complexo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Complete the code for the `squareList` function using any combination of `map()`, `filter()`, and `reduce()`. The function should return a new array containing the squares of *only* the positive integers (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array of real numbers is `[-3, 4.8, 5, 3, -3.2]`.
|
||||
Complete o código para a função `squareList` usando qualquer combinação de `map()`, `filter()` e `reduce()`. A função deve retornar uma nova matriz contendo *apenas* os inteiros positivos (números decimais não são inteiros) elevados ao quadrado quando uma matriz de números reais é passada para ela. Um exemplo de array de números reais é `[-3, 4.8, 5, 3, -3.2]`.
|
||||
|
||||
**Note:** Your function should not use any kind of `for` or `while` loops or the `forEach()` function.
|
||||
**Obs:** Você não deve usar os loops `for` ou `while` ou a função `forEach()` na sua função.
|
||||
|
||||
# --hints--
|
||||
|
||||
`squareList` should be a `function`.
|
||||
`squareList` deve ser uma <dfn>função</dfn>.
|
||||
|
||||
```js
|
||||
assert.typeOf(squareList, 'function'),
|
||||
'<code>squareList</code> should be a <code>function</code>';
|
||||
```
|
||||
|
||||
`for`, `while`, and `forEach` should not be used.
|
||||
Loops `for`, `while`e a função `forEach` não devem ser usados.
|
||||
|
||||
```js
|
||||
assert(!code.match(/for|while|forEach/g));
|
||||
```
|
||||
|
||||
`map`, `filter`, or `reduce` should be used.
|
||||
`map`, `filter` ou `reduce` deve ser usado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -41,13 +41,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The function should return an `array`.
|
||||
A função deve retornar um `array`.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
|
||||
```
|
||||
|
||||
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` should return `[16, 1764, 36]`.
|
||||
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` deve retornar `[16, 1764, 36]`.
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
|
||||
@ -57,7 +57,7 @@ assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` should return `[9, 100, 49]`.
|
||||
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` deve retornar `[9, 100, 49]`.
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6e
|
||||
title: Use the every Method to Check that Every Element in an Array Meets a Criteria
|
||||
title: Use o Método every para Checar Se Todos os Elementos em um Array Atendem a um Critério
|
||||
challengeType: 1
|
||||
forumTopicId: 301312
|
||||
dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria
|
||||
@ -8,9 +8,9 @@ dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a
|
||||
|
||||
# --description--
|
||||
|
||||
The `every` method works with arrays to check if *every* element passes a particular test. It returns a Boolean value - `true` if all values meet the criteria, `false` if not.
|
||||
O método `every` funciona verificando se *todos* os elementos de um array passam em um teste. Ele retorna um booleano: `true` se todos os valores atendem ao critério e `false` caso contrário.
|
||||
|
||||
For example, the following code would check if every element in the `numbers` array is less than 10:
|
||||
Por exemplo, o código a seguir verifica se todos os elementos no array `numbers` são menores que 10:
|
||||
|
||||
```js
|
||||
var numbers = [1, 5, 8, 0, 10, 11];
|
||||
@ -19,33 +19,33 @@ numbers.every(function(currentValue) {
|
||||
});
|
||||
```
|
||||
|
||||
The `every` method would return `false` here.
|
||||
O método `every` retorna `false` neste exemplo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `every` method inside the `checkPositive` function to check if every element in `arr` is positive. The function should return a Boolean value.
|
||||
Use o método `every` dentro da função `checkPositive` para checar se todos os elementos em `arr` são positivos. A função deve retornar um valor booleano.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `every` method.
|
||||
Você deve usar o método `every`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.every/g));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, -4, 5])` should return `false`.
|
||||
`checkPositive([1, 2, 3, -4, 5])` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
|
||||
`checkPositive([1, 2, 3, 4, 5])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, -2, 3, -4, 5])` should return `false`.
|
||||
`checkPositive([1, -2, 3, -4, 5])` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(checkPositive([1, -2, 3, -4, 5]));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b63
|
||||
title: Use the filter Method to Extract Data from an Array
|
||||
title: Use o Método filter para Extrair Dados de um Array
|
||||
challengeType: 1
|
||||
forumTopicId: 18179
|
||||
dashedName: use-the-filter-method-to-extract-data-from-an-array
|
||||
@ -8,13 +8,13 @@ dashedName: use-the-filter-method-to-extract-data-from-an-array
|
||||
|
||||
# --description--
|
||||
|
||||
Another useful array function is `Array.prototype.filter()`, or simply `filter()`.
|
||||
Outra função útil de array é `Array.prototype.filter()`, ou simplesmente `filter()`.
|
||||
|
||||
`filter` calls a function on each element of an array and returns a new array containing only the elements for which that function returns `true`. In other words, it filters the array, based on the function passed to it. Like `map`, it does this without needing to modify the original array.
|
||||
O `filter` chama uma função para cada elemento de um array e constrói um novo array contendo apenas os elementos para os quais a função retorna `true`. Em outras palavras, ele filtra o array de acordo com a função passada a ele. Ele o faz sem alterar o array original assim como `map`.
|
||||
|
||||
The callback function accepts three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `filter` method was called.
|
||||
A função callback toma três argumentos. O primeiro argumento é o elemento que está a ser processado. O segundo é o índice deste elemento e o terceiro é o array do qual `filter` foi chamado.
|
||||
|
||||
See below for an example using the `filter` method on the `users` array to return a new array containing only the users under the age of 30. For simplicity, the example only uses the first argument of the callback.
|
||||
Abaixo você vê um exemplo do `filter` sendo usado do array `users` para retornar um novo array apenas com os usuários cuja idade é menor que 30. O exemplo usa apenas o primeiro argumento do callback por simplicidade.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
@ -27,15 +27,15 @@ const usersUnder30 = users.filter(user => user.age < 30);
|
||||
console.log(usersUnder30);
|
||||
```
|
||||
|
||||
The console would display the value `[ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]`.
|
||||
O console mostraria o valor `[ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The variable `watchList` holds an array of objects with information on several movies. Use a combination of `filter` and `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys. The new array should only include objects where `imdbRating` is greater than or equal to 8.0. Note that the `rating` values are saved as strings in the object and you may need to convert them into numbers to perform mathematical operations on them.
|
||||
A variável `watchList` armazena um array de objetos com informações de diversos filmes. Use uma combinação de `filter` e `map` em `watchList` para criar um novo array de objetos apenas com as chaves `title` e `rating`. O novo array deve incluir apenas os objetos cujo `imdbRating` é maior que ou igual a 8. Observe que os valores de `rating` são salvos como strings nos objetos, então você pode precisar convertê-los para números antes de realizar operações matemáticas com eles.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `watchList` variable should not change.
|
||||
A variável `watchList` não deve ser alterada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,19 +43,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your code should use the `filter` method.
|
||||
Você deve usar o método `filter`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\s*\.\s*filter/g));
|
||||
```
|
||||
|
||||
Your code should not use a `for` loop.
|
||||
Você não deve usar loops `for`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
|
||||
```
|
||||
|
||||
`filteredList` should equal `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`.
|
||||
`filteredList` deve ser igual a `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(filteredList, [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b61
|
||||
title: Use the map Method to Extract Data from an Array
|
||||
title: Use o Método map para Extrair Dados de um Array
|
||||
challengeType: 1
|
||||
forumTopicId: 18214
|
||||
dashedName: use-the-map-method-to-extract-data-from-an-array
|
||||
@ -8,19 +8,19 @@ dashedName: use-the-map-method-to-extract-data-from-an-array
|
||||
|
||||
# --description--
|
||||
|
||||
So far we have learned to use pure functions to avoid side effects in a program. Also, we have seen the value in having a function only depend on its input arguments.
|
||||
Até então nós aprendemos a usar funções puras para evitar efeitos colaterais em um programa. Vimos também que há valor em fazer funções dependerem apenas de suas entradas.
|
||||
|
||||
This is only the beginning. As its name suggests, functional programming is centered around a theory of functions.
|
||||
Este é apenas o começo. Como o nome sugere, programação funcional orbita uma teoria de funções.
|
||||
|
||||
It would make sense to be able to pass them as arguments to other functions, and return a function from another function. Functions are considered <dfn>first class objects</dfn> in JavaScript, which means they can be used like any other object. They can be saved in variables, stored in an object, or passed as function arguments.
|
||||
Faz sentido conseguir passar funções como argumento a outras funções e retorná-las de outras funções. Funções são consideradas <dfn>objetos de primeira classe</dfn> em JavaScript e podem ser usadas como qualquer outro objeto. Elas podem ser salvas em variáveis, objetos ou passadas como argumento a funções.
|
||||
|
||||
Let's start with some simple array functions, which are methods on the array object prototype. In this exercise we are looking at `Array.prototype.map()`, or more simply `map`.
|
||||
Vamos começar com algumas funções simples de array. Alguns métodos no protótipo de objetos array. Neste exercício estamos de olho em `Array.prototype.map()`, ou simplesmente `map`.
|
||||
|
||||
The `map` method iterates over each item in an array and returns a new array containing the results of calling the callback function on each element. It does this without mutating the original array.
|
||||
O método `map` percorre cada item de um array e retorna um novo array cujos elementos são os resultados da chamada do callback para cada item. Isso tudo acontece sem modificar o array original.
|
||||
|
||||
When the callback is used, it is passed three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `map` method was called.
|
||||
A função callback é chamada com três argumentos. O primeiro argumento é o elemento que está a ser processado. O segundo é o índice deste elemento e o terceiro é o array do qual `map` foi chamado.
|
||||
|
||||
See below for an example using the `map` method on the `users` array to return a new array containing only the names of the users as elements. For simplicity, the example only uses the first argument of the callback.
|
||||
Abaixo você vê um exemplo do `map` sendo usado do array `users` para retornar um novo array apenas com os nomes dos usuários. O exemplo usa apenas o primeiro argumento do callback por simplicidade.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
@ -33,15 +33,15 @@ const names = users.map(user => user.name);
|
||||
console.log(names);
|
||||
```
|
||||
|
||||
The console would display the value `[ 'John', 'Amy', 'camperCat' ]`.
|
||||
O console mostraria o valor `[ 'John', 'Amy', 'camperCat' ]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The `watchList` array holds objects with information on several movies. Use `map` on `watchList` to assign a new array of objects to the `ratings` variable. Each movie in the new array should have only a `title` key with the name of the film, and a `rating` key with the IMDB rating. The code in the editor currently uses a `for` loop to do this, so you should replace the loop functionality with your `map` expression.
|
||||
A variável `watchList` armazena um array de objetos com informações de diversos filmes. Use o `map` na `watchList` para atribuir uma nova matriz de objetos à variável</code>ratins`. Cada filme no novo array deve ter apenas um <code>title` com o nome do filme, e uma chave `rating` com a classificação do IMDB. O código atual no editor usa um loop `for` para fazer isso, então você deve substituir o laço com sua expressão `map`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `watchList` variable should not change.
|
||||
A variável `watchList` não deve ser alterada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -49,19 +49,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your code should not use a `for` loop.
|
||||
Você não deve usar loops `for`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/));
|
||||
```
|
||||
|
||||
Your code should use the `map` method.
|
||||
Você deve usar o método `map`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.map/g));
|
||||
```
|
||||
|
||||
`ratings` should equal `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`.
|
||||
`ratings` deve ser igual a `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(ratings, [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b68
|
||||
title: Use the reduce Method to Analyze Data
|
||||
title: Use o Método reduce para Analisar Dados
|
||||
challengeType: 1
|
||||
forumTopicId: 301313
|
||||
dashedName: use-the-reduce-method-to-analyze-data
|
||||
@ -8,15 +8,15 @@ dashedName: use-the-reduce-method-to-analyze-data
|
||||
|
||||
# --description--
|
||||
|
||||
`Array.prototype.reduce()`, or simply `reduce()`, is the most general of all array operations in JavaScript. You can solve almost any array processing problem using the `reduce` method.
|
||||
`Array.prototype.reduce()`, ou simplesmente `reduce()`, realiza as operações mais gerais de todas as operações de array em JavaScript. Você pode resolver quase qualquer problema de processamento de array usando o método `reduce`.
|
||||
|
||||
The `reduce` method allows for more general forms of array processing, and it's possible to show that both `filter` and `map` can be derived as special applications of `reduce`. The `reduce` method iterates over each item in an array and returns a single value (i.e. string, number, object, array). This is achieved via a callback function that is called on each iteration.
|
||||
O método `reduce` permite formas mais gerais de processamento de array, e é possível mostrar que tanto o `filter` quanto o `map` podem ser derivados como aplicações especiais de `reduce`. O método `reduce` percorre cada elemento de um array e retorna um valor (uma string, um número, um objeto ou array). Isso é factível através de um callback que é chamado para cada elemento.
|
||||
|
||||
The callback function accepts four arguments. The first argument is known as the accumulator, which gets assigned the return value of the callback function from the previous iteration, the second is the current element being processed, the third is the index of that element and the fourth is the array upon which `reduce` is called.
|
||||
A função callback toma quatro argumentos. O primeiro argumento é conhecido como o acumulador, ao qual é atribuído o resultado do callback na iteração anterior. O segundo é o elemento a ser processado. O terceiro é o índice do elemento e o quarto é o array do qual `reduce` foi chamado.
|
||||
|
||||
In addition to the callback function, `reduce` has an additional parameter which takes an initial value for the accumulator. If this second parameter is not used, then the first iteration is skipped and the second iteration gets passed the first element of the array as the accumulator.
|
||||
Além da função callback, `reduce` tem um parâmetro adicional que recebe um valor inicial para o acumulador. Se o segundo parâmetro não for usado, então a primeira iteração é ignorada e ao acumulador é atribuído o primeiro elemento do array na segunda iteração.
|
||||
|
||||
See below for an example using `reduce` on the `users` array to return the sum of all the users' ages. For simplicity, the example only uses the first and second arguments.
|
||||
Veja abaixo um exemplo usando `reduce` no array `users` para retornar a soma de todas as idades de todos os usuários. O exemplo usa apenas os dois primeiros argumentos pela simplicidade.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
@ -29,9 +29,9 @@ const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
|
||||
console.log(sumOfAges);
|
||||
```
|
||||
|
||||
The console would display the value `64`.
|
||||
O console mostra o valor `64`.
|
||||
|
||||
In another example, see how an object can be returned containing the names of the users as properties with their ages as values.
|
||||
No próximo exemplo abaixo, veja como um objeto pode ser retornado contendo os nomes dos usuários como chaves e suas idades como valores.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
@ -47,15 +47,15 @@ const usersObj = users.reduce((obj, user) => {
|
||||
console.log(usersObj);
|
||||
```
|
||||
|
||||
The console would display the value `{ John: 34, Amy: 20, camperCat: 10 }`.
|
||||
O console mostra o valor `{ John: 34, Amy: 20, camperCat: 10 }`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The variable `watchList` holds an array of objects with information on several movies. Use `reduce` to find the average IMDB rating of the movies directed by `Christopher Nolan`. Recall from prior challenges how to `filter` data and `map` over it to pull what you need. You may need to create other variables, and return the average rating from `getRating` function. Note that the rating values are saved as strings in the object and need to be converted into numbers before they are used in any mathematical operations.
|
||||
A variável `watchList` armazena um array de objetos com informações de diversos filmes. Use `reduce` para encontrar a média da classificação IMDB dos filmes direcionados por `Christopher Nolan`. Você já aprendeu em desafios passados como filtrar e mapear dados de array com `filter` e `map`. Você pode precisar usar outras variáveis para retornar a nota média da função `getRating`. Observe que os valores das notas estão salvas como strings nos objetos e precisam ser convertidos para números antes que possam ser usados em operações matemáticas.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `watchList` variable should not change.
|
||||
A variável `watchList` não deve ser alterada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -63,25 +63,25 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your code should use the `reduce` method.
|
||||
Você deve usar o método `reduce`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.reduce/g));
|
||||
```
|
||||
|
||||
The `getRating(watchList)` should equal 8.675.
|
||||
`getRating(watchList)` deve ser igual a 8.675.
|
||||
|
||||
```js
|
||||
assert(getRating(watchList) === 8.675);
|
||||
```
|
||||
|
||||
Your code should not use a `for` loop.
|
||||
Você não deve usar loops `for`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
|
||||
```
|
||||
|
||||
Your code should return the correct output after modifying the `watchList` object.
|
||||
Sua função deve retornar o valor correto após manipular `watchList` com filter, map e reduce.
|
||||
|
||||
```js
|
||||
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6f
|
||||
title: Use the some Method to Check that Any Elements in an Array Meet a Criteria
|
||||
title: Use o Método some para Checar Se Pelo Menos Um Elemento em um Array Atende a um Critério
|
||||
challengeType: 1
|
||||
forumTopicId: 301314
|
||||
dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria
|
||||
@ -8,9 +8,9 @@ dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-cr
|
||||
|
||||
# --description--
|
||||
|
||||
The `some` method works with arrays to check if *any* element passes a particular test. It returns a Boolean value - `true` if any of the values meet the criteria, `false` if not.
|
||||
O método `some` funciona verificando se *pelo menos um* dos elementos de um array passam em um teste. Ele retorna um booleano: `true` se pelo menos um valor atende ao critério e `false` caso contrário.
|
||||
|
||||
For example, the following code would check if any element in the `numbers` array is less than 10:
|
||||
Por exemplo, o código a seguir verifica se qualquer elemento no array `numbers` é menor que 10:
|
||||
|
||||
```js
|
||||
var numbers = [10, 50, 8, 220, 110, 11];
|
||||
@ -19,33 +19,33 @@ numbers.some(function(currentValue) {
|
||||
});
|
||||
```
|
||||
|
||||
The `some` method would return `true`.
|
||||
O método `some` retorna `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `some` method inside the `checkPositive` function to check if any element in `arr` is positive. The function should return a Boolean value.
|
||||
Use o método `some` na função `checkPositive` para verificar se algum elemento em `arr` é positivo. A função deve retornar um valor booleano.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `some` method.
|
||||
Você deve usar o método `some`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.some/g));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, -4, 5])` should return `true`.
|
||||
`checkPositive([1, 2, 3, -4, 5])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(checkPositive([1, 2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
|
||||
`checkPositive([1, 2, 3, 4, 5])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(checkPositive([1, 2, 3, 4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([-1, -2, -3, -4, -5])` should return `false`.
|
||||
`checkPositive([-1, -2, -3, -4, -5])` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(!checkPositive([-1, -2, -3, -4, -5]));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a97fd23d9b809dac9921074f
|
||||
title: Arguments Optional
|
||||
title: Argumentos Opcionais
|
||||
challengeType: 5
|
||||
forumTopicId: 14271
|
||||
dashedName: arguments-optional
|
||||
@ -8,53 +8,53 @@ dashedName: arguments-optional
|
||||
|
||||
# --description--
|
||||
|
||||
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.
|
||||
Crie uma função que some dois argumentos juntos. Se apenas um argumento for fornecido, então retorne uma função que espera um argumento e retorna a sua soma.
|
||||
|
||||
For example, `addTogether(2, 3)` should return `5`, and `addTogether(2)` should return a function.
|
||||
Por exemplo, `addTogether(2, 3)` deve retornar `5` e `addTogether(2)` deve retornar uma função.
|
||||
|
||||
Calling this returned function with a single argument will then return the sum:
|
||||
Chamando essa função retornada com um argumento retornará a soma:
|
||||
|
||||
```js
|
||||
var sumTwoAnd = addTogether(2);
|
||||
```
|
||||
|
||||
`sumTwoAnd(3)` returns `5`.
|
||||
`sumTwoAnd(3)` retorna `5`.
|
||||
|
||||
If either argument isn't a valid number, return undefined.
|
||||
Se algum argumento não for um número válido, retorne undefined.
|
||||
|
||||
# --hints--
|
||||
|
||||
`addTogether(2, 3)` should return 5.
|
||||
`addTogether(2, 3)` deve retornar 5.
|
||||
|
||||
```js
|
||||
assert.deepEqual(addTogether(2, 3), 5);
|
||||
```
|
||||
|
||||
`addTogether(23, 30)` should return 53.
|
||||
`addTogether(23, 30)` deve retornar 53.
|
||||
|
||||
```js
|
||||
assert.deepEqual(addTogether(23, 30), 53);
|
||||
```
|
||||
|
||||
`addTogether(5)(7)` should return 12.
|
||||
`addTogether(5)(7)` deve retornar 12.
|
||||
|
||||
```js
|
||||
assert.deepEqual(addTogether(5)(7), 12);
|
||||
```
|
||||
|
||||
`addTogether("http://bit.ly/IqT6zt")` should return `undefined`.
|
||||
`addTogether("http://bit.ly/IqT6zt")` deve retornar `undefined`.
|
||||
|
||||
```js
|
||||
assert.isUndefined(addTogether('http://bit.ly/IqT6zt'));
|
||||
```
|
||||
|
||||
`addTogether(2, "3")` should return `undefined`.
|
||||
`addTogether(2, "3")` deve retornar `undefined`.
|
||||
|
||||
```js
|
||||
assert.isUndefined(addTogether(2, '3'));
|
||||
```
|
||||
|
||||
`addTogether(2)([3])` should return `undefined`.
|
||||
`addTogether(2)([3])` deve retornar `undefined`.
|
||||
|
||||
```js
|
||||
assert.isUndefined(addTogether(2)([3]));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a8d97bd4c764e91f9d2bda01
|
||||
title: Binary Agents
|
||||
title: Agentes Binários
|
||||
challengeType: 5
|
||||
forumTopicId: 14273
|
||||
dashedName: binary-agents
|
||||
@ -8,13 +8,13 @@ dashedName: binary-agents
|
||||
|
||||
# --description--
|
||||
|
||||
Return an English translated sentence of the passed binary string.
|
||||
Retorne uma frase traduzida em Inglês da string binária passada.
|
||||
|
||||
The binary string will be space separated.
|
||||
A string binária será separada por espaço.
|
||||
|
||||
# --hints--
|
||||
|
||||
`binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111")` should return the string `Aren't bonfires fun!?`
|
||||
`binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111")` deve retornar a string `Aren't bonfires fun!?`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -25,7 +25,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001")` should return the string `I love FreeCodeCamp!`
|
||||
`binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001")` deve retornar a string `I love FreeCodeCamp!`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a6b0bb188d873cb2c8729495
|
||||
title: Convert HTML Entities
|
||||
title: Converter Entidades HTML
|
||||
challengeType: 5
|
||||
forumTopicId: 16007
|
||||
dashedName: convert-html-entities
|
||||
@ -8,17 +8,17 @@ dashedName: convert-html-entities
|
||||
|
||||
# --description--
|
||||
|
||||
Convert the characters `&`, `<`, `>`, `"` (double quote), and `'` (apostrophe), in a string to their corresponding HTML entities.
|
||||
Converta os caracteres `&`, `<`, `>`, `"` (aspas duplas) e `'` (aspas simples), em uma string para suas entidades HTML correspondentes.
|
||||
|
||||
# --hints--
|
||||
|
||||
`convertHTML("Dolce & Gabbana")` should return the string `Dolce & Gabbana`.
|
||||
`convertHTML("Dolce & Gabbana")` deve retorna a string `Dolce & Gabbana`.
|
||||
|
||||
```js
|
||||
assert.match(convertHTML('Dolce & Gabbana'), /Dolce & Gabbana/);
|
||||
```
|
||||
|
||||
`convertHTML("Hamburgers < Pizza < Tacos")` should return the string `Hamburgers < Pizza < Tacos`.
|
||||
`convertHTML("Hamburgers < Pizza < Tacos")` deve retornar a string `Hamburgers < Pizza < Tacos`.
|
||||
|
||||
```js
|
||||
assert.match(
|
||||
@ -27,13 +27,13 @@ assert.match(
|
||||
);
|
||||
```
|
||||
|
||||
`convertHTML("Sixty > twelve")` should return the string `Sixty > twelve`.
|
||||
`convertHTML("Sixty > twelve")` deve retornar a string `Sixty > twelve`.
|
||||
|
||||
```js
|
||||
assert.match(convertHTML('Sixty > twelve'), /Sixty > twelve/);
|
||||
```
|
||||
|
||||
`convertHTML('Stuff in "quotation marks"')` should return the string `Stuff in "quotation marks"`.
|
||||
`convertHTML('Stuff in "quotation marks"')` deve retornar a string `Stuff in "quotation marks"`.
|
||||
|
||||
```js
|
||||
assert.match(
|
||||
@ -42,19 +42,19 @@ assert.match(
|
||||
);
|
||||
```
|
||||
|
||||
`convertHTML("Schindler's List")` should return the string `Schindler's List`.
|
||||
`convertHTML("Schindler's List")` deve retornar a string `Schindler's List`.
|
||||
|
||||
```js
|
||||
assert.match(convertHTML("Schindler's List"), /Schindler's List/);
|
||||
```
|
||||
|
||||
`convertHTML("<>")` should return the string `<>`.
|
||||
`convertHTML("<>")` deve retornar a string `<>`.
|
||||
|
||||
```js
|
||||
assert.match(convertHTML('<>'), /<>/);
|
||||
```
|
||||
|
||||
`convertHTML("abc")` should return the string `abc`.
|
||||
`convertHTML("abc")` deve retornar a string `abc`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(convertHTML('abc'), 'abc');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a5de63ebea8dbee56860f4f2
|
||||
title: Diff Two Arrays
|
||||
title: Diferenciar Dois Arrays
|
||||
challengeType: 5
|
||||
forumTopicId: 16008
|
||||
dashedName: diff-two-arrays
|
||||
@ -8,19 +8,19 @@ dashedName: diff-two-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
|
||||
Compare dois arrays e retorne um novo array com qualquer item encontrado em apenas um dos dois arrays passados, mas não ambos. Em outras palavras, retorne a diferença simétrica de dois arrays.
|
||||
|
||||
**Note:** You can return the array with its elements in any order.
|
||||
**Nota:** Você pode retornar o array com seus elementos em qualquer ordem.
|
||||
|
||||
# --hints--
|
||||
|
||||
`diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])` should return an array.
|
||||
`diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(typeof diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) === 'object');
|
||||
```
|
||||
|
||||
`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` should return `["pink wool"]`.
|
||||
`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` deve retornar `["pink wool"]`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
@ -32,7 +32,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` should return an array with one item.
|
||||
`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` deve retornar um array com um item.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,7 +43,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` should return `["diorite", "pink wool"]`.
|
||||
`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` deve retornar `["diorite", "pink wool"]`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
@ -55,7 +55,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` should return an array with two items.
|
||||
`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` deve retornar um array com dois itens.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -66,7 +66,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` should return `[]`.
|
||||
`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` deve retornar `[]`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
@ -78,7 +78,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` should return an empty array.
|
||||
`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` deve retornar um array vazio.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -89,19 +89,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`[1, 2, 3, 5], [1, 2, 3, 4, 5]` should return `[4]`.
|
||||
`[1, 2, 3, 5], [1, 2, 3, 4, 5]` deve retornar `[4]`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), [4]);
|
||||
```
|
||||
|
||||
`[1, 2, 3, 5], [1, 2, 3, 4, 5]` should return an array with one item.
|
||||
`[1, 2, 3, 5], [1, 2, 3, 4, 5]` deve retornar um array com um item.
|
||||
|
||||
```js
|
||||
assert(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]).length === 1);
|
||||
```
|
||||
|
||||
`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` should return `["piglet", 4]`.
|
||||
`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` deve retornar `["piglet", 4]`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]), [
|
||||
@ -110,13 +110,13 @@ assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` should return an array with two items.
|
||||
`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` deve retornar um array com dois itens.
|
||||
|
||||
```js
|
||||
assert(diffArray([1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]).length === 2);
|
||||
```
|
||||
|
||||
`[], ["snuffleupagus", "cookie monster", "elmo"]` should return `["snuffleupagus", "cookie monster", "elmo"]`.
|
||||
`[], ["snuffleupagus", "cookie monster", "elmo"]` deve retornar `["snuffleupagus", "cookie monster", "elmo"]`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(diffArray([], ['snuffleupagus', 'cookie monster', 'elmo']), [
|
||||
@ -126,13 +126,13 @@ assert.sameMembers(diffArray([], ['snuffleupagus', 'cookie monster', 'elmo']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`[], ["snuffleupagus", "cookie monster", "elmo"]` should return an array with three items.
|
||||
`[], ["snuffleupagus", "cookie monster", "elmo"]` deve retornar um array com três itens.
|
||||
|
||||
```js
|
||||
assert(diffArray([], ['snuffleupagus', 'cookie monster', 'elmo']).length === 3);
|
||||
```
|
||||
|
||||
`[1, "calf", 3, "piglet"], [7, "filly"]` should return `[1, "calf", 3, "piglet", 7, "filly"]`.
|
||||
`[1, "calf", 3, "piglet"], [7, "filly"]` deve retornar `[1, "calf", 3, "piglet", 7, "filly"]`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [7, 'filly']), [
|
||||
@ -145,7 +145,7 @@ assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [7, 'filly']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`[1, "calf", 3, "piglet"], [7, "filly"]` should return an array with six items.
|
||||
`[1, "calf", 3, "piglet"], [7, "filly"]` deve retornar um array com seis itens.
|
||||
|
||||
```js
|
||||
assert(diffArray([1, 'calf', 3, 'piglet'], [7, 'filly']).length === 6);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: afd15382cdfb22c9efe8b7de
|
||||
title: DNA Pairing
|
||||
title: Pareamento de DNA
|
||||
challengeType: 5
|
||||
forumTopicId: 16009
|
||||
dashedName: dna-pairing
|
||||
@ -8,19 +8,19 @@ dashedName: dna-pairing
|
||||
|
||||
# --description--
|
||||
|
||||
The DNA strand is missing the pairing element. Take each character, get its pair, and return the results as a 2d array.
|
||||
A faixa de DNA está faltando o elemento de pareamento. Pegue cada caractere, pegue seu par e retorne os resultados como um array de duas dimensões.
|
||||
|
||||
[Base pairs](http://en.wikipedia.org/wiki/Base_pair) are a pair of AT and CG. Match the missing element to the provided character.
|
||||
[Pares de base](http://en.wikipedia.org/wiki/Base_pair) são pares de AT e CG. Associe o elemento faltando para o caractere fornecido.
|
||||
|
||||
Return the provided character as the first element in each array.
|
||||
Retorne o caractere fornecido como o primeiro elemento em cada array.
|
||||
|
||||
For example, for the input `GCG`, return `[["G", "C"], ["C","G"], ["G", "C"]]`
|
||||
Por exemplo, para a entrada `GCG`, retorne `[["G", "C"], ["C","G"], ["G", "C"]]`
|
||||
|
||||
The character and its pair are paired up in an array, and all the arrays are grouped into one encapsulating array.
|
||||
O caractere e seu par estão emparelhados em um array, e todos os arrays estão agrupados em um array encapsulador.
|
||||
|
||||
# --hints--
|
||||
|
||||
`pairElement("ATCGA")` should return `[["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]]`.
|
||||
`pairElement("ATCGA")` deve retornar `[["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pairElement('ATCGA'), [
|
||||
@ -32,7 +32,7 @@ assert.deepEqual(pairElement('ATCGA'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`pairElement("TTGAG")` should return `[["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]]`.
|
||||
`pairElement("TTGAG")` deve retornar `[["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pairElement('TTGAG'), [
|
||||
@ -44,7 +44,7 @@ assert.deepEqual(pairElement('TTGAG'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`pairElement("CTCTA")` should return `[["C","G"],["T","A"],["C","G"],["T","A"],["A","T"]]`.
|
||||
`pairElement("CTCTA")` deve retornar `[["C","G"],["T","A"],["C","G"],["T","A"],["A","T"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pairElement('CTCTA'), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a5deed1811a43193f9f1c841
|
||||
title: Drop it
|
||||
title: Solte isso
|
||||
challengeType: 5
|
||||
forumTopicId: 16010
|
||||
dashedName: drop-it
|
||||
@ -8,13 +8,13 @@ dashedName: drop-it
|
||||
|
||||
# --description--
|
||||
|
||||
Given the array `arr`, iterate through and remove each element starting from the first element (the 0 index) until the function `func` returns `true` when the iterated element is passed through it.
|
||||
Dado o array `arr`, faça iterações sobre ele e remova cada elemento começando do primeiro elemento (o índice 0) até que a função `func` retorne `true` quando o elemento iterado for passado através dele.
|
||||
|
||||
Then return the rest of the array once the condition is satisfied, otherwise, `arr` should be returned as an empty array.
|
||||
Em seguida, retorne o resto do array uma vez que a condição for satisfeita, caso contrário, `arr` deve ser retornado como um array vazio.
|
||||
|
||||
# --hints--
|
||||
|
||||
`dropElements([1, 2, 3, 4], function(n) {return n >= 3;})` should return `[3, 4]`.
|
||||
`dropElements([1, 2, 3, 4], function(n) {return n >= 3;})` deve retornar `[3, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -25,7 +25,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`dropElements([0, 1, 0, 1], function(n) {return n === 1;})` should return `[1, 0, 1]`.
|
||||
`dropElements([0, 1, 0, 1], function(n) {return n === 1;})` deve retornar `[1, 0, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -36,7 +36,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`dropElements([1, 2, 3], function(n) {return n > 0;})` should return `[1, 2, 3]`.
|
||||
`dropElements([1, 2, 3], function(n) {return n > 0;})` deve retornar `[1, 2, 3]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -47,7 +47,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`dropElements([1, 2, 3, 4], function(n) {return n > 5;})` should return `[]`.
|
||||
`dropElements([1, 2, 3, 4], function(n) {return n > 5;})` deve retornar `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -58,7 +58,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;})` should return `[7, 4]`.
|
||||
`dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;})` deve retornar `[7, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -69,7 +69,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})` should return `[3, 9, 2]`.
|
||||
`dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})` deve retornar `[3, 9, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a10d2431ad0c6a099a4b8b52
|
||||
title: Everything Be True
|
||||
title: Tudo Seja Verdadeiro
|
||||
challengeType: 5
|
||||
forumTopicId: 16011
|
||||
dashedName: everything-be-true
|
||||
@ -8,17 +8,17 @@ dashedName: everything-be-true
|
||||
|
||||
# --description--
|
||||
|
||||
Check if the predicate (second argument) is <dfn>truthy</dfn> on all elements of a collection (first argument).
|
||||
Verifique se o predicado (segundo argumento) é <dfn>truthy</dfn> em todos os elementos de uma coleção (primeiro argumento).
|
||||
|
||||
In other words, you are given an array collection of objects. The predicate `pre` will be an object property and you need to return `true` if its value is `truthy`. Otherwise, return `false`.
|
||||
Em outras palavras, você recebe uma coleção de array de objetos. O predicado `pre` será uma propriedade de objeto e você precisa retornar `true` se seu valor for `truthy`. Caso contrário, retorne `false`.
|
||||
|
||||
In JavaScript, `truthy` values are values that translate to `true` when evaluated in a Boolean context.
|
||||
Em JavaScript, valores </code>truthy` são valores que traduzem para <code>true` quando avaliados em um contexto booleano.
|
||||
|
||||
Remember, you can access object properties through either dot notation or `[]` notation.
|
||||
Lembre-se, você pode acessar propriedades de objeto através de notação de ponto ou notação `[]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` should return `true`.
|
||||
`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -35,7 +35,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` should return `false`.
|
||||
`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -52,7 +52,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age")` should return `false`.
|
||||
`truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -69,7 +69,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastForward", "onBoat": null}], "onBoat")` should return `false`.
|
||||
`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastForward", "onBoat": null}], "onBoat")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -85,7 +85,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastForward", "onBoat": true}], "onBoat")` should return `true`.
|
||||
`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastForward", "onBoat": true}], "onBoat")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -101,13 +101,13 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`truthCheck([{"single": "yes"}], "single")` should return `true`.
|
||||
`truthCheck([{"single": "yes"}], "single")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(truthCheck([{ single: 'yes' }], 'single'), true);
|
||||
```
|
||||
|
||||
`truthCheck([{"single": ""}, {"single": "double"}], "single")` should return `false`.
|
||||
`truthCheck([{"single": ""}, {"single": "double"}], "single")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -116,7 +116,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`truthCheck([{"single": "double"}, {"single": undefined}], "single")` should return `false`.
|
||||
`truthCheck([{"single": "double"}, {"single": undefined}], "single")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -125,7 +125,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`truthCheck([{"single": "double"}, {"single": NaN}], "single")` should return `false`.
|
||||
`truthCheck([{"single": "double"}, {"single": NaN}], "single")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a2f1d72d9b908d0bd72bb9f6
|
||||
title: Make a Person
|
||||
title: Faça uma Pessoa
|
||||
challengeType: 5
|
||||
forumTopicId: 16020
|
||||
dashedName: make-a-person
|
||||
@ -8,7 +8,7 @@ dashedName: make-a-person
|
||||
|
||||
# --description--
|
||||
|
||||
Fill in the object constructor with the following methods below:
|
||||
Preencha o construtor do objeto com os seguintes métodos abaixo:
|
||||
|
||||
```js
|
||||
getFirstName()
|
||||
@ -19,53 +19,53 @@ setLastName(last)
|
||||
setFullName(firstAndLast)
|
||||
```
|
||||
|
||||
Run the tests to see the expected output for each method. The methods that take an argument must accept only one argument and it has to be a string. These methods must be the only available means of interacting with the object.
|
||||
Execute os testes para ver a saída esperada para cada método. Os métodos que recebem um argumento têm de aceitar apenas um argumento e tem de ser uma string. Estes métodos devem constituir o único meio de interação com o objeto.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Object.keys(bob).length` should return 6.
|
||||
`Object.keys(bob).length` deve retornar 6.
|
||||
|
||||
```js
|
||||
assert.deepEqual(Object.keys(bob).length, 6);
|
||||
```
|
||||
|
||||
`bob instanceof Person` should return `true`.
|
||||
`bob instanceof Pessoa` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bob instanceof Person, true);
|
||||
```
|
||||
|
||||
`bob.firstName` should return `undefined`.
|
||||
`bob.firstName` deve retornar `undefined`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bob.firstName, undefined);
|
||||
```
|
||||
|
||||
`bob.lastName` should return `undefined`.
|
||||
`bob.lastName` deve retornar `undefined`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bob.lastName, undefined);
|
||||
```
|
||||
|
||||
`bob.getFirstName()` should return the string `Bob`.
|
||||
`bob.getFirstName()` deve retornar a string `Bob`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bob.getFirstName(), 'Bob');
|
||||
```
|
||||
|
||||
`bob.getLastName()` should return the string `Ross`.
|
||||
`bob.getLastName()` deve retornar a string `Ross`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bob.getLastName(), 'Ross');
|
||||
```
|
||||
|
||||
`bob.getFullName()` should return the string `Bob Ross`.
|
||||
`bob.getFullName()` deve retornar a string `Bob Ross`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bob.getFullName(), 'Bob Ross');
|
||||
```
|
||||
|
||||
`bob.getFullName()` should return the string `Haskell Ross` after `bob.setFirstName("Haskell")`.
|
||||
`bob.getFullName()` deve retornar a string `Haskell Ross` após `bob.setFirstName("Haskell")`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -77,7 +77,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`bob.getFullName()` should return the string `Haskell Curry` after `bob.setLastName("Curry")`.
|
||||
`bob.getFullName()` deve retornar a string `Haskell Curry` após `bob.setLastName("Curry")`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -90,7 +90,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`bob.getFullName()` should return the string `Haskell Curry` after `bob.setFullName("Haskell Curry")`.
|
||||
`bob.getFullName()` deve retornar a string `Haskell Curry` após `bob.setFullName("Haskell Curry")`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -102,7 +102,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`bob.getFirstName()` should return the string `Haskell` after `bob.setFullName("Haskell Curry")`.
|
||||
`bob.getFirstName()` deve retornar a string `Haskell` após `bob.setFullName("Haskell Curry")`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -114,7 +114,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`bob.getLastName()` should return the string `Curry` after `bob.setFullName("Haskell Curry")`.
|
||||
`bob.getLastName()` deve retornar a string `Curry` após `bob.setFullName("Haskell Curry")`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: af4afb223120f7348cdfc9fd
|
||||
title: Map the Debris
|
||||
title: Mapear o Debris
|
||||
challengeType: 5
|
||||
forumTopicId: 16021
|
||||
dashedName: map-the-debris
|
||||
@ -8,19 +8,19 @@ dashedName: map-the-debris
|
||||
|
||||
# --description--
|
||||
|
||||
Return a new array that transforms the elements' average altitude into their orbital periods (in seconds).
|
||||
Retorna um novo array que transforma a altitude média dos elementos em seus períodos órbita (em segundos).
|
||||
|
||||
The array will contain objects in the format `{name: 'name', avgAlt: avgAlt}`.
|
||||
O array conterá objetos no formato `{name: 'name', avgAlt: avgAlt}`.
|
||||
|
||||
You can read about orbital periods [on Wikipedia](http://en.wikipedia.org/wiki/Orbital_period).
|
||||
Você pode ler sobre períodos de órbita [na Wikipedia](http://en.wikipedia.org/wiki/Orbital_period).
|
||||
|
||||
The values should be rounded to the nearest whole number. The body being orbited is Earth.
|
||||
Os valores devem estar arredondados para o número inteiro mais próximo. O corpo sendo orbitado é a Terra.
|
||||
|
||||
The radius of the earth is 6367.4447 kilometers, and the GM value of earth is 398600.4418 km<sup>3</sup>s<sup>-2</sup>.
|
||||
O raio da terra é 6367,4447 quilômetros, e o valor de GM da térra é 398600,4418 km<sup>3</sup>s<sup>-2</sup>.
|
||||
|
||||
# --hints--
|
||||
|
||||
`orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}])` should return `[{name: "sputnik", orbitalPeriod: 86400}]`.
|
||||
`orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}])` deve retornar `[{name: "sputnik", orbitalPeriod: 86400}]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(orbitalPeriod([{ name: 'sputnik', avgAlt: 35873.5553 }]), [
|
||||
@ -28,7 +28,7 @@ assert.deepEqual(orbitalPeriod([{ name: 'sputnik', avgAlt: 35873.5553 }]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}])` should return `[{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}]`.
|
||||
`orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}])` deve retornar `[{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: af7588ade1100bde429baf20
|
||||
title: Missing letters
|
||||
title: Letras faltando
|
||||
challengeType: 5
|
||||
forumTopicId: 16023
|
||||
dashedName: missing-letters
|
||||
@ -8,37 +8,37 @@ dashedName: missing-letters
|
||||
|
||||
# --description--
|
||||
|
||||
Find the missing letter in the passed letter range and return it.
|
||||
Encontre a letra que falta no intervalo de letras passado e devolva-a.
|
||||
|
||||
If all letters are present in the range, return `undefined`.
|
||||
Se todas as letras estiverem presentes no intervalo, retorne `undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`fearNotLetter("abce")` should return the string `d`.
|
||||
`fearNotLetter("abce")` deve retornar a string `d`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fearNotLetter('abce'), 'd');
|
||||
```
|
||||
|
||||
`fearNotLetter("abcdefghjklmno")` should return the string `i`.
|
||||
`fearNotLetter("abcdefghjklmno")` deve retornar a string `i`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fearNotLetter('abcdefghjklmno'), 'i');
|
||||
```
|
||||
|
||||
`fearNotLetter("stvwx")` should return the string `u`.
|
||||
`fearNotLetter("stvwx")` deve retornar a string `u`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fearNotLetter('stvwx'), 'u');
|
||||
```
|
||||
|
||||
`fearNotLetter("bcdf")` should return the string `e`.
|
||||
`fearNotLetter("bcdf")` deve retornar a string `e`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fearNotLetter('bcdf'), 'e');
|
||||
```
|
||||
|
||||
`fearNotLetter("abcdefghijklmnopqrstuvwxyz")` should return `undefined`.
|
||||
`fearNotLetter("abcdefghijklmnopqrstuvwxyz")` deve retornar `undefined`.
|
||||
|
||||
```js
|
||||
assert.isUndefined(fearNotLetter('abcdefghijklmnopqrstuvwxyz'));
|
||||
|
@ -8,55 +8,55 @@ dashedName: pig-latin
|
||||
|
||||
# --description--
|
||||
|
||||
Pig Latin is a way of altering English Words. The rules are as follows:
|
||||
Pig Latin é uma forma de alterar palavras inglesas. As regras são as seguintes:
|
||||
|
||||
\- If a word begins with a consonant, take the first consonant or consonant cluster, move it to the end of the word, and add `ay` to it.
|
||||
\- Se uma palavra começar com uma consoante, tire a primeira consoante ou grupo de consoantes, mova-a para o final da palavra e adicione `ay` a ela.
|
||||
|
||||
\- If a word begins with a vowel, just add `way` at the end.
|
||||
\- Se uma palavra começar com uma vogal, basta adicionar `way` no final.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Translate the provided string to Pig Latin. Input strings are guaranteed to be English words in all lowercase.
|
||||
Traduza a string fornecida para o Pig Latin. As strings de entrada terão a garantia de serem palavras em inglês com as letras em minúsculo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`translatePigLatin("california")` should return the string `aliforniacay`.
|
||||
`translatePigLatin("california")` deve retornar a string `aliforniacay`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(translatePigLatin('california'), 'aliforniacay');
|
||||
```
|
||||
|
||||
`translatePigLatin("paragraphs")` should return the string `aragraphspay`.
|
||||
`translatePigLatin("paragraphs")` deve retornar a string `aragraphspay`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(translatePigLatin('paragraphs'), 'aragraphspay');
|
||||
```
|
||||
|
||||
`translatePigLatin("glove")` should return the string `oveglay`.
|
||||
`translatePigLatin("glove")` deve retornar a string `oveglay`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(translatePigLatin('glove'), 'oveglay');
|
||||
```
|
||||
|
||||
`translatePigLatin("algorithm")` should return the string `algorithmway`.
|
||||
`translatePigLatin("algorithm")` deve retornar a string `algorithmway`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(translatePigLatin('algorithm'), 'algorithmway');
|
||||
```
|
||||
|
||||
`translatePigLatin("eight")` should return the string `eightway`.
|
||||
`translatePigLatin("eight")` deve retornar a string `eightway`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(translatePigLatin('eight'), 'eightway');
|
||||
```
|
||||
|
||||
Should handle words where the first vowel comes in the middle of the word. `translatePigLatin("schwartz")` should return the string `artzschway`.
|
||||
Deve lidar com palavras onde a primeira vogal vem no meio da palavra. `translatePigLatin("schwartz")` deve retornar a string `artzschway`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(translatePigLatin('schwartz'), 'artzschway');
|
||||
```
|
||||
|
||||
Should handle words without vowels. `translatePigLatin("rhythm")` should return the string `rhythmay`.
|
||||
Deve lidar com palavras sem vogais. `translatePigLatin("rhythm")` deve retornar a string `rhythmay`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(translatePigLatin('rhythm'), 'rhythmay');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a0b5010f579e69b815e7c5d6
|
||||
title: Search and Replace
|
||||
title: Procurar e substituir
|
||||
challengeType: 5
|
||||
forumTopicId: 16045
|
||||
dashedName: search-and-replace
|
||||
@ -8,19 +8,19 @@ dashedName: search-and-replace
|
||||
|
||||
# --description--
|
||||
|
||||
Perform a search and replace on the sentence using the arguments provided and return the new sentence.
|
||||
Realize uma busca e substitua na frase usando os argumentos fornecidos e retorne a nova frase.
|
||||
|
||||
First argument is the sentence to perform the search and replace on.
|
||||
O primeiro argumento é a frase para realizar a busca e substituir.
|
||||
|
||||
Second argument is the word that you will be replacing (before).
|
||||
O segundo argumento é a palavra que você substituirá (antes).
|
||||
|
||||
Third argument is what you will be replacing the second argument with (after).
|
||||
O terceiro argumento é com o que você irá substituir o segundo argumento (depois).
|
||||
|
||||
**Note:** Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word `Book` with the word `dog`, it should be replaced as `Dog`
|
||||
**Nota:** Preserve a capitalização do primeiro caractere na palavra original quando você estiver substituindo. Por exemplo, se você quiser substituir a palavra `Book` com a palavra `dog`, deve ser substituído com `Dog`
|
||||
|
||||
# --hints--
|
||||
|
||||
`myReplace("Let us go to the store", "store", "mall")` should return the string `Let us go to the mall`.
|
||||
`myReplace("Let us go to the store", "store", "mall")` deve retornar a string `Let us go to the mall`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -29,7 +29,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myReplace("He is Sleeping on the couch", "Sleeping", "sitting")` should return the string `He is Sitting on the couch`.
|
||||
`myReplace("He is Sleeping on the couch", "Sleeping", "sitting")` deve retornar a string `He is Sitting on the couch`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -38,7 +38,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myReplace("I think we should look up there", "up", "Down")` should return the string `I think we should look down there`.
|
||||
`myReplace("I think we should look up there", "up", "Down")` deve retornar a string `I think we should look down there`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -47,7 +47,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myReplace("This has a spellngi error", "spellngi", "spelling")` should return the string `This has a spelling error`.
|
||||
`myReplace("This has a spellngi error", "spellngi", "spelling")` deve retornar a string `This has a spelling error`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -56,7 +56,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myReplace("His name is Tom", "Tom", "john")` should return the string `His name is John`.
|
||||
`myReplace("His name is Tom", "Tom", "john")` deve retornar a string `His name is John`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -65,7 +65,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myReplace("Let us get back to more Coding", "Coding", "algorithms")` should return the string `Let us get back to more Algorithms`.
|
||||
`myReplace("Let us get back to more Coding", "Coding", "algorithms")` deve retornar a string `Let us get back to more Algorithms`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a39963a4c10bc8b4d4f06d7e
|
||||
title: Seek and Destroy
|
||||
title: Procurar e Destruir
|
||||
challengeType: 5
|
||||
forumTopicId: 16046
|
||||
dashedName: seek-and-destroy
|
||||
@ -8,37 +8,37 @@ dashedName: seek-and-destroy
|
||||
|
||||
# --description--
|
||||
|
||||
You will be provided with an initial array (the first argument in the `destroyer` function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
|
||||
Você receberá um array inicial (o primeiro argumento na função `destroyer`), seguido por um ou mais argumentos. Remova todos os elementos da matriz inicial que são do mesmo valor que esses argumentos.
|
||||
|
||||
**Note:** You have to use the `arguments` object.
|
||||
**Nota:** Você tem que usar os `argumentos` do objeto.
|
||||
|
||||
# --hints--
|
||||
|
||||
`destroyer([1, 2, 3, 1, 2, 3], 2, 3)` should return `[1, 1]`.
|
||||
`destroyer([1, 2, 3, 1, 2, 3], 2, 3)` deve retornar `[1, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(destroyer([1, 2, 3, 1, 2, 3], 2, 3), [1, 1]);
|
||||
```
|
||||
|
||||
`destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3)` should return `[1, 5, 1]`.
|
||||
`destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3)` deve retornar `[1, 5, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3), [1, 5, 1]);
|
||||
```
|
||||
|
||||
`destroyer([3, 5, 1, 2, 2], 2, 3, 5)` should return `[1]`.
|
||||
`destroyer([3, 5, 1, 2, 2], 2, 3, 5)` deve retornar `[1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(destroyer([3, 5, 1, 2, 2], 2, 3, 5), [1]);
|
||||
```
|
||||
|
||||
`destroyer([2, 3, 2, 3], 2, 3)` should return `[]`.
|
||||
`destroyer([2, 3, 2, 3], 2, 3)` deve retornar `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(destroyer([2, 3, 2, 3], 2, 3), []);
|
||||
```
|
||||
|
||||
`destroyer(["tree", "hamburger", 53], "tree", 53)` should return `["hamburger"]`.
|
||||
`destroyer(["tree", "hamburger", 53], "tree", 53)` deve retornar `["hamburger"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(destroyer(['tree', 'hamburger', 53], 'tree', 53), [
|
||||
@ -46,7 +46,7 @@ assert.deepEqual(destroyer(['tree', 'hamburger', 53], 'tree', 53), [
|
||||
]);
|
||||
```
|
||||
|
||||
`destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan")` should return `[12,92,65]`.
|
||||
`destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan")` deve retornar `[12,92,65]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: ae9defd7acaf69703ab432ea
|
||||
title: Smallest Common Multiple
|
||||
title: Menores Múltiplos Comuns
|
||||
challengeType: 5
|
||||
forumTopicId: 16075
|
||||
dashedName: smallest-common-multiple
|
||||
@ -8,45 +8,45 @@ dashedName: smallest-common-multiple
|
||||
|
||||
# --description--
|
||||
|
||||
Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters.
|
||||
Encontre o menor múltiplo comum dos parâmetros fornecidos que podem ser divididos sem resto por ambos, bem como por todos os números sequenciais no intervalo entre esses parâmetros.
|
||||
|
||||
The range will be an array of two numbers that will not necessarily be in numerical order.
|
||||
O intervalo será um array de dois números que não estará necessariamente em ordem numérica.
|
||||
|
||||
For example, if given 1 and 3, find the smallest common multiple of both 1 and 3 that is also evenly divisible by all numbers *between* 1 and 3. The answer here would be 6.
|
||||
Por exemplo, se forem dados 1 e 3, encontre o menor múltiplo comum de 1 e 3 que também é divisível por todos os números *entre* 1 e 3. A resposta aqui seria 6.
|
||||
|
||||
# --hints--
|
||||
|
||||
`smallestCommons([1, 5])` should return a number.
|
||||
`smallestCommons([1, 5])` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert.deepEqual(typeof smallestCommons([1, 5]), 'number');
|
||||
```
|
||||
|
||||
`smallestCommons([1, 5])` should return 60.
|
||||
`smallestCommons([1, 5])` deve retornar 60.
|
||||
|
||||
```js
|
||||
assert.deepEqual(smallestCommons([1, 5]), 60);
|
||||
```
|
||||
|
||||
`smallestCommons([5, 1])` should return 60.
|
||||
`smallestCommons([5, 1])` deve retornar 60.
|
||||
|
||||
```js
|
||||
assert.deepEqual(smallestCommons([5, 1]), 60);
|
||||
```
|
||||
|
||||
`smallestCommons([2, 10])` should return 2520.
|
||||
`smallestCommons([2, 10])` deve retornar 2520.
|
||||
|
||||
```js
|
||||
assert.deepEqual(smallestCommons([2, 10]), 2520);
|
||||
```
|
||||
|
||||
`smallestCommons([1, 13])` should return 360360.
|
||||
`smallestCommons([1, 13])` deve retornar 360360.
|
||||
|
||||
```js
|
||||
assert.deepEqual(smallestCommons([1, 13]), 360360);
|
||||
```
|
||||
|
||||
`smallestCommons([23, 18])` should return 6056820.
|
||||
`smallestCommons([23, 18])` retornará 6056820.
|
||||
|
||||
```js
|
||||
assert.deepEqual(smallestCommons([23, 18]), 6056820);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a105e963526e7de52b219be9
|
||||
title: Sorted Union
|
||||
title: União ordenada
|
||||
challengeType: 5
|
||||
forumTopicId: 16077
|
||||
dashedName: sorted-union
|
||||
@ -8,29 +8,29 @@ dashedName: sorted-union
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.
|
||||
Escreva uma função que recebe dois ou mais arrays e retorne um novo array de calores únicos na ordem do array original fornecido.
|
||||
|
||||
In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.
|
||||
Em outras palavras, todos os valores presentes de todos os arrays devem ser incluídos na sua ordem original, mas sem valores duplicados no array final.
|
||||
|
||||
The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.
|
||||
Os números únicos devem ser ordenados pela sua ordem original, mas o array final não deve ser ordenado em ordem numérica.
|
||||
|
||||
Check the assertion tests for examples.
|
||||
Verifique os testes de asserção para exemplos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1])` should return `[1, 3, 2, 5, 4]`.
|
||||
`uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1])` deve retornar `[1, 3, 2, 5, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]), [1, 3, 2, 5, 4]);
|
||||
```
|
||||
|
||||
`uniteUnique([1, 2, 3], [5, 2, 1])` should return `[1, 2, 3, 5]`.
|
||||
`uniteUnique([1, 2, 3], [5, 2, 1])` deve retornar `[1, 2, 3, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1]), [1, 2, 3, 5]);
|
||||
```
|
||||
|
||||
`uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8])` should return `[1, 2, 3, 5, 4, 6, 7, 8]`.
|
||||
`uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8])` deve retornar `[1, 2, 3, 5, 4, 6, 7, 8]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a103376db3ba46b2d50db289
|
||||
title: Spinal Tap Case
|
||||
title: Caso de Toque Espinal
|
||||
challengeType: 5
|
||||
forumTopicId: 16078
|
||||
dashedName: spinal-tap-case
|
||||
@ -8,23 +8,23 @@ dashedName: spinal-tap-case
|
||||
|
||||
# --description--
|
||||
|
||||
Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.
|
||||
Converta uma string para um caso espinal. Casos espinais são todas-as-palavras-minúsculas-unidas-por-traços.
|
||||
|
||||
# --hints--
|
||||
|
||||
`spinalCase("This Is Spinal Tap")` should return the string `this-is-spinal-tap`.
|
||||
`spinalCase("This Is Spinal Tap")` deve retornar a string `this-is-spinal-tap`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(spinalCase('This Is Spinal Tap'), 'this-is-spinal-tap');
|
||||
```
|
||||
|
||||
`spinalCase("thisIsSpinalTap")` should return the string `this-is-spinal-tap`.
|
||||
`spinalCase("thisIsSpinalTap")` deve retornar a string `this-is-spinal-tap`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(spinalCase('thisIsSpinalTap'), 'this-is-spinal-tap');
|
||||
```
|
||||
|
||||
`spinalCase("The_Andy_Griffith_Show")` should return the string `the-andy-griffith-show`.
|
||||
`spinalCase("The_Andy_Griffith_Show")` deve retornar a string `the-andy-griffith-show`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -33,7 +33,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`spinalCase("Teletubbies say Eh-oh")` should return the string `teletubbies-say-eh-oh`.
|
||||
`spinalCase("Teletubbies say Eh-oh")` deve retornar a string `teletubbies-say-eh-oh`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -42,7 +42,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`spinalCase("AllThe-small Things")` should return the string `all-the-small-things`.
|
||||
`spinalCase("AllThe-small Things")` deve retornar a string `all-the-small-things`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(spinalCase('AllThe-small Things'), 'all-the-small-things');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: ab306dbdcc907c7ddfc30830
|
||||
title: Steamroller
|
||||
title: Rolo compressor
|
||||
challengeType: 5
|
||||
forumTopicId: 16079
|
||||
dashedName: steamroller
|
||||
@ -8,35 +8,35 @@ dashedName: steamroller
|
||||
|
||||
# --description--
|
||||
|
||||
Flatten a nested array. You must account for varying levels of nesting.
|
||||
Achate um array aninhado. Você deve lidar com diferentes níveis de aninhamento.
|
||||
|
||||
# --hints--
|
||||
|
||||
`steamrollArray([[["a"]], [["b"]]])` should return `["a", "b"]`.
|
||||
`steamrollArray([[["a"]], [["b"]]])` deve retornar `["a", "b"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(steamrollArray([[['a']], [['b']]]), ['a', 'b']);
|
||||
```
|
||||
|
||||
`steamrollArray([1, [2], [3, [[4]]]])` should return `[1, 2, 3, 4]`.
|
||||
`steamrollArray([1, [2], [3, [[4]]]])` deve retornar `[1, 2, 3, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(steamrollArray([1, [2], [3, [[4]]]]), [1, 2, 3, 4]);
|
||||
```
|
||||
|
||||
`steamrollArray([1, [], [3, [[4]]]])` should return `[1, 3, 4]`.
|
||||
`steamrollArray([1, [], [3, [[4]]]])` deve retornar `[1, 3, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(steamrollArray([1, [], [3, [[4]]]]), [1, 3, 4]);
|
||||
```
|
||||
|
||||
`steamrollArray([1, {}, [3, [[4]]]])` should return `[1, {}, 3, 4]`.
|
||||
`steamrollArray([1, {}, [3, [[4]]]])` deve retornar `[1, {}, 3, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(steamrollArray([1, {}, [3, [[4]]]]), [1, {}, 3, 4]);
|
||||
```
|
||||
|
||||
Your solution should not use the `Array.prototype.flat()` or `Array.prototype.flatMap()` methods.
|
||||
Sua solução não deve usar os métodos `Array.prototype.flat()` ou `Array.prototype.flatMap()`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.\s*flat\s*\(/) && !code.match(/\.\s*flatMap\s*\(/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a3566b1109230028080c9345
|
||||
title: Sum All Numbers in a Range
|
||||
title: Soma Todos os Números em um intervalo
|
||||
challengeType: 5
|
||||
forumTopicId: 16083
|
||||
dashedName: sum-all-numbers-in-a-range
|
||||
@ -8,37 +8,37 @@ dashedName: sum-all-numbers-in-a-range
|
||||
|
||||
# --description--
|
||||
|
||||
We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first.
|
||||
Vamos passar um array de dois números. Retorne a soma desses dois números mais a soma de todos os números entre eles. O menor número nem sempre chegará primeiro.
|
||||
|
||||
For example, `sumAll([4,1])` should return `10` because sum of all the numbers between 1 and 4 (both inclusive) is `10`.
|
||||
Por exemplo, `somAll([4, 1])` deve retornar `10` porque a soma de todos os números entre 1 e 4 (ambos incluídos) é `10`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumAll([1, 4])` should return a number.
|
||||
`sumAll([1, 4])` deve ser um número.
|
||||
|
||||
```js
|
||||
assert(typeof sumAll([1, 4]) === 'number');
|
||||
```
|
||||
|
||||
`sumAll([1, 4])` should return 10.
|
||||
`sumAll([1, 4])` deve retornar 10.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumAll([1, 4]), 10);
|
||||
```
|
||||
|
||||
`sumAll([4, 1])` should return 10.
|
||||
`sumAll([4, 1])` deve retornar 10.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumAll([4, 1]), 10);
|
||||
```
|
||||
|
||||
`sumAll([5, 10])` should return 45.
|
||||
`sumAll([5, 10])` deve retornar 45.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumAll([5, 10]), 45);
|
||||
```
|
||||
|
||||
`sumAll([10, 5])` should return 45.
|
||||
`sumAll([10, 5])` deve retornar 45.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumAll([10, 5]), 45);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a5229172f011153519423690
|
||||
title: Sum All Odd Fibonacci Numbers
|
||||
title: Soma todos os números ímpares de Fibonacci
|
||||
challengeType: 5
|
||||
forumTopicId: 16084
|
||||
dashedName: sum-all-odd-fibonacci-numbers
|
||||
@ -8,45 +8,45 @@ dashedName: sum-all-odd-fibonacci-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
Given a positive integer `num`, return the sum of all odd Fibonacci numbers that are less than or equal to `num`.
|
||||
Dado um `num` inteiro e positivo, retorne a soma de todos os números ímpares Fibonacci menores que ou iguais a `num`.
|
||||
|
||||
The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.
|
||||
Os dois primeiros números na sequência de Fibonacci são 1 e 1. Todo número adicional na sequência é a soma dos dois números anteriores. Os seis primeiros números da sequência de Fibonacci são 1, 1, 2, 3, 5 e 8.
|
||||
|
||||
For example, `sumFibs(10)` should return `10` because all odd Fibonacci numbers less than or equal to `10` are 1, 1, 3, and 5.
|
||||
Por exemplo, `sumFibs(10)` deve retornar `10` porque todos os números ímpares de Fibonacci menores ou iguais a `10` são 1, 1, 3 e 5.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumFibs(1)` should return a number.
|
||||
`sumFibs(1)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof sumFibs(1) === 'number');
|
||||
```
|
||||
|
||||
`sumFibs(1000)` should return 1785.
|
||||
`sumFibs(1000)` deve retornar 1785.
|
||||
|
||||
```js
|
||||
assert(sumFibs(1000) === 1785);
|
||||
```
|
||||
|
||||
`sumFibs(4000000)` should return 4613732.
|
||||
`sumFibs(4000000)` deve retornar 4613732.
|
||||
|
||||
```js
|
||||
assert(sumFibs(4000000) === 4613732);
|
||||
```
|
||||
|
||||
`sumFibs(4)` should return 5.
|
||||
`sumFibs(4)` deve retornar 5.
|
||||
|
||||
```js
|
||||
assert(sumFibs(4) === 5);
|
||||
```
|
||||
|
||||
`sumFibs(75024)` should return 60696.
|
||||
`sumFibs(75024)` deve retornar 60696.
|
||||
|
||||
```js
|
||||
assert(sumFibs(75024) === 60696);
|
||||
```
|
||||
|
||||
`sumFibs(75025)` should return 135721.
|
||||
`sumFibs(75025)` deve retornar 135721.
|
||||
|
||||
```js
|
||||
assert(sumFibs(75025) === 135721);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a3bfc1673c0526e06d3ac698
|
||||
title: Sum All Primes
|
||||
title: Somar Todos os Primos
|
||||
challengeType: 5
|
||||
forumTopicId: 16085
|
||||
dashedName: sum-all-primes
|
||||
@ -8,25 +8,25 @@ dashedName: sum-all-primes
|
||||
|
||||
# --description--
|
||||
|
||||
A <dfn>prime number</dfn> is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
|
||||
Um <dfn>número primo</dfn> é um número natural maior que 1 com exatamente dois divisores: 1 e ele mesmo. Por exemplo, 2 é um número primo porque só é divisível por 1 e 2. Em contrapartida, 4 não é primo, uma vez que é divisível por 1, 2 e 4.
|
||||
|
||||
Rewrite `sumPrimes` so it returns the sum of all prime numbers that are less than or equal to num.
|
||||
Reescreva `sumPrimes` para que ele retorne a soma de todos os números primos que são menores ou iguais a num.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumPrimes(10)` should return a number.
|
||||
`sumPrimes(10)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert.deepEqual(typeof sumPrimes(10), 'number');
|
||||
```
|
||||
|
||||
`sumPrimes(10)` should return 17.
|
||||
`sumPrimes(10)` deve retornar 17.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumPrimes(10), 17);
|
||||
```
|
||||
|
||||
`sumPrimes(977)` should return 73156.
|
||||
`sumPrimes(977)` deve retornar 73156.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumPrimes(977), 73156);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a8e512fbe388ac2f9198f0fa
|
||||
title: Wherefore art thou
|
||||
title: Onde está você
|
||||
challengeType: 5
|
||||
forumTopicId: 16092
|
||||
dashedName: wherefore-art-thou
|
||||
@ -8,13 +8,13 @@ dashedName: wherefore-art-thou
|
||||
|
||||
# --description--
|
||||
|
||||
Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
|
||||
Faça uma função que olha através de um array de objetos (primeiro argumento) e retorna um array de todos os objetos que têm pares de nome e valor correspondentes (segundo argumento). Cada par de nome e valor do objeto fonte tem que estar presente no objeto da coleção se ele for ser incluído no array retornado.
|
||||
|
||||
For example, if the first argument is `[{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]`, and the second argument is `{ last: "Capulet" }`, then you must return the third object from the array (the first argument), because it contains the name and its value, that was passed on as the second argument.
|
||||
Por exemplo, se o primeiro argumento é `[{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]`, e o segundo argumento é `{ last: "Capulet" }`, em seguida, você deve retornar o terceiro objeto do array (o primeiro argumento), porque contém o nome e o seu valor, que foi passado como segundo argumento.
|
||||
|
||||
# --hints--
|
||||
|
||||
`whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })` should return `[{ first: "Tybalt", last: "Capulet" }]`.
|
||||
`whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })` deve retornar `[{ first: "Tybalt", last: "Capulet" }]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -30,7 +30,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 })` should return `[{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }]`.
|
||||
`whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 })` deve retornar `[{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -41,7 +41,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })` should return `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }]`.
|
||||
`whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })` deve retornar `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -56,7 +56,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 })` should return `[{ "apple": 1, "bat": 2, "cookie": 2 }]`.
|
||||
`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 })` deve retornar `[{ "apple": 1, "bat": 2, "cookie": 2 }]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -68,7 +68,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })` should return `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]`.
|
||||
`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })` deve retornar `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -88,7 +88,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3})` should return `[]`
|
||||
`whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3})` deve retornar `[]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244e2
|
||||
title: Caesars Cipher
|
||||
title: Cifra de César
|
||||
challengeType: 5
|
||||
forumTopicId: 16003
|
||||
dashedName: caesars-cipher
|
||||
@ -8,35 +8,35 @@ dashedName: caesars-cipher
|
||||
|
||||
# --description--
|
||||
|
||||
One of the simplest and most widely known <dfn>ciphers</dfn> is a <dfn>Caesar cipher</dfn>, also known as a <dfn>shift cipher</dfn>. In a shift cipher the meanings of the letters are shifted by some set amount.
|
||||
Uma das <dfn>cifras</dfn> mais simples e mais conhecidas é a <dfn>cifra de César</dfn>, também conhecida como uma <dfn>cifra de mudança</dfn>. Em uma cifra de transferência, os significados das letras são deslocados de acordo com a quantidade definida.
|
||||
|
||||
A common modern use is the [ROT13](https://en.wikipedia.org/wiki/ROT13) cipher, where the values of the letters are shifted by 13 places. Thus `A ↔ N`, `B ↔ O` and so on.
|
||||
Um uso moderno comum é a cifra [ROT13](https://en.wikipedia.org/wiki/ROT13), onde os valores das letras são deslocados em 13 lugares. Da seguinte forma: `A ↔ N`, `B ↔ O` e assim por diante.
|
||||
|
||||
Write a function which takes a [ROT13](https://en.wikipedia.org/wiki/ROT13) encoded string as input and returns a decoded string.
|
||||
Escreva uma função que recebe uma string codificada de [ROT13](https://en.wikipedia.org/wiki/ROT13) como entrada e retorna uma string decodificada.
|
||||
|
||||
All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.
|
||||
Todas as letras serão maiúsculas. Não transforme nenhum caractere não-alfabético (ou seja, espaços, pontuação), mas passe por eles.
|
||||
|
||||
# --hints--
|
||||
|
||||
`rot13("SERR PBQR PNZC")` should decode to the string `FREE CODE CAMP`
|
||||
`rot13("SERR PBQR PNZC")` deve decodificar para a string `FREE CODE CAMP`
|
||||
|
||||
```js
|
||||
assert(rot13('SERR PBQR PNZC') === 'FREE CODE CAMP');
|
||||
```
|
||||
|
||||
`rot13("SERR CVMMN!")` should decode to the string `FREE PIZZA!`
|
||||
`rot13("SERR CVMMN!")` deve decodificar para a string `FREE PIZZA!`
|
||||
|
||||
```js
|
||||
assert(rot13('SERR CVMMN!') === 'FREE PIZZA!');
|
||||
```
|
||||
|
||||
`rot13("SERR YBIR?")` should decode to the string `FREE LOVE?`
|
||||
`rot13("SERR YBIR?")` deve decodificar para a string `FREE LOVE?`
|
||||
|
||||
```js
|
||||
assert(rot13('SERR YBIR?') === 'FREE LOVE?');
|
||||
```
|
||||
|
||||
`rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.")` should decode to the string `THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.`
|
||||
`rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.")`deve decodificar para a string `THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: aa2e6f85cab2ab736c9a9b24
|
||||
title: Cash Register
|
||||
title: Caixa Registradora
|
||||
challengeType: 5
|
||||
forumTopicId: 16012
|
||||
dashedName: cash-register
|
||||
@ -8,21 +8,21 @@ dashedName: cash-register
|
||||
|
||||
# --description--
|
||||
|
||||
Design a cash register drawer function `checkCashRegister()` that accepts purchase price as the first argument (`price`), payment as the second argument (`cash`), and cash-in-drawer (`cid`) as the third argument.
|
||||
Implemente uma função de registradora de caixa `checkCashRegister()` que aceita o preço de compra como o primeiro argumento (`price`), pagamento como o segundo argumento (`cash`) e dinheiro na registradora (`cid`) como o terceiro argumento.
|
||||
|
||||
`cid` is a 2D array listing available currency.
|
||||
`cid` é um array de duas dimensões listando a moeda disponível e a quantidade.
|
||||
|
||||
The `checkCashRegister()` function should always return an object with a `status` key and a `change` key.
|
||||
A função `checkCashRegister()` deve sempre retornar um objeto com a chave `status` e uma chave `change`.
|
||||
|
||||
Return `{status: "INSUFFICIENT_FUNDS", change: []}` if cash-in-drawer is less than the change due, or if you cannot return the exact change.
|
||||
Retorne `{status: "INSUFFICIENT_FUNDS", change: []}` se o dinheiro no caixa for menor que o troco devido, ou se você não pode retornar o troco exato.
|
||||
|
||||
Return `{status: "CLOSED", change: [...]}` with cash-in-drawer as the value for the key `change` if it is equal to the change due.
|
||||
Retorne `{status: "CLOSED", change: [...]}` com dinheiro no caixa como o valor para a chave `change` se for igual ao troco devido.
|
||||
|
||||
Otherwise, return `{status: "OPEN", change: [...]}`, with the change due in coins and bills, sorted in highest to lowest order, as the value of the `change` key.
|
||||
Caso contrário, retorne `{status: "OPEN", change: [...]}`, com o troco devido em moedas e notas, ordenado do maior para o menor, como o valor da chave `change`.
|
||||
|
||||
<table class='table table-striped'><tbody><tr><th>Currency Unit</th><th>Amount</th></tr><tr><td>Penny</td><td>$0.01 (PENNY)</td></tr><tr><td>Nickel</td><td>$0.05 (NICKEL)</td></tr><tr><td>Dime</td><td>$0.1 (DIME)</td></tr><tr><td>Quarter</td><td>$0.25 (QUARTER)</td></tr><tr><td>Dollar</td><td>$1 (ONE)</td></tr><tr><td>Five Dollars</td><td>$5 (FIVE)</td></tr><tr><td>Ten Dollars</td><td>$10 (TEN)</td></tr><tr><td>Twenty Dollars</td><td>$20 (TWENTY)</td></tr><tr><td>One-hundred Dollars</td><td>$100 (ONE HUNDRED)</td></tr></tbody></table>
|
||||
<table class='table table-striped'><tbody><tr><th>Unidade de moeda</th><th>Quantidade</th></tr><tr><td>Penny</td><td>$0,01 (MET)</td></tr><tr><td>Níquel</td><td>$0,05 (NICKEL)</td></tr><tr><td>Dime</td><td>$0,1 (DIME)</td></tr><tr><td>Quarter</td><td>$0,25 (QUARTER)</td></tr><tr><td>Dólar</td><td>$1 (UM)</td></tr><tr><td>Cinco Dólares</td><td>$5 (CINCO)</td></tr><tr><td>Dez Dólares</td><td>$10 (DEZ)</td></tr><tr><td>Vinte Dólares</td><td>$20 (VINTE)</td></tr><tr><td>Cem Dólares</td><td>$100 (CEM)</td></tr></tbody></table>
|
||||
|
||||
See below for an example of a cash-in-drawer array:
|
||||
Veja abaixo um exemplo de um array de dinheiro no caixa (cid):
|
||||
|
||||
```js
|
||||
[
|
||||
@ -40,7 +40,7 @@ See below for an example of a cash-in-drawer array:
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` should return an object.
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` deve retornar um objeto.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -61,7 +61,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` should return `{status: "OPEN", change: [["QUARTER", 0.5]]}`.
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` deve retornar `{status: "OPEN", change: [["QUARTER", 0.5]]}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -80,7 +80,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` should return `{status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}`.
|
||||
`checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` deve retornar `{status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -110,7 +110,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` should return `{status: "INSUFFICIENT_FUNDS", change: []}`.
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` deve retornar `{status: "INSUFFICIENT_FUNDS", change: []}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -129,7 +129,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` should return `{status: "INSUFFICIENT_FUNDS", change: []}`.
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` deve retornar `{status: "INSUFFICIENT_FUNDS", change: []}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -148,7 +148,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` should return `{status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}`.
|
||||
`checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` deve retornar `{status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: aaa48de84e1ecc7c742e1124
|
||||
title: Palindrome Checker
|
||||
title: Verificador de Palíndromo
|
||||
challengeType: 5
|
||||
forumTopicId: 16004
|
||||
dashedName: palindrome-checker
|
||||
@ -8,91 +8,91 @@ dashedName: palindrome-checker
|
||||
|
||||
# --description--
|
||||
|
||||
Return `true` if the given string is a palindrome. Otherwise, return `false`.
|
||||
Retorne `true` se a string fornecida for um palíndromo. Caso contrário, retorne `false`.
|
||||
|
||||
A <dfn>palindrome</dfn> is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.
|
||||
Um <dfn>palíndromo</dfn> é uma palavra ou frase que é dita da mesma maneira na ordem natural que na ordem inversa, ignorando pontuação, capitalização e espaçamento.
|
||||
|
||||
**Note:** You'll need to remove **all non-alphanumeric characters** (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes.
|
||||
**Nota:** Você precisará remover **todos os caracteres não alfanuméricos** (pontuação, espaços e símbolos) e transforme tudo na mesma capitalização (letra em minúsculo ou maiúsculo) para verificar se determinada palavra ou frase é um palíndromo.
|
||||
|
||||
We'll pass strings with varying formats, such as `racecar`, `RaceCar`, and `race CAR` among others.
|
||||
Vamos passar strings em diferentes formatos, como `racecar`, `RaceCarar` e `race CAR` entre outros.
|
||||
|
||||
We'll also pass strings with special symbols, such as `2A3*3a2`, `2A3 3a2`, and `2_A3*3#A2`.
|
||||
Nós também passaremos strings com símbolos especiais, como `2A3*3a2`, `2A3 3a2` e `2_A3*3#A2`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`palindrome("eye")` should return a boolean.
|
||||
`palindrome("eye")` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof palindrome('eye') === 'boolean');
|
||||
```
|
||||
|
||||
`palindrome("eye")` should return `true`.
|
||||
`palindrome("eye")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(palindrome('eye') === true);
|
||||
```
|
||||
|
||||
`palindrome("_eye")` should return `true`.
|
||||
`palindrome("_eye")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(palindrome('_eye') === true);
|
||||
```
|
||||
|
||||
`palindrome("race car")` should return `true`.
|
||||
`palindrome("race car")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(palindrome('race car') === true);
|
||||
```
|
||||
|
||||
`palindrome("not a palindrome")` should return `false`.
|
||||
`palindrome("not a palindrome")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(palindrome('not a palindrome') === false);
|
||||
```
|
||||
|
||||
`palindrome("A man, a plan, a canal. Panama")` should return `true`.
|
||||
`palindrome("A man, a plan, a canal. Panama")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(palindrome('A man, a plan, a canal. Panama') === true);
|
||||
```
|
||||
|
||||
`palindrome("never odd or even")` should return `true`.
|
||||
`palindrome("never odd or even")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(palindrome('never odd or even') === true);
|
||||
```
|
||||
|
||||
`palindrome("nope")` should return `false`.
|
||||
`palindrome("nope")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(palindrome('nope') === false);
|
||||
```
|
||||
|
||||
`palindrome("almostomla")` should return `false`.
|
||||
`palindrome("almostomla")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(palindrome('almostomla') === false);
|
||||
```
|
||||
|
||||
`palindrome("My age is 0, 0 si ega ym.")` should return `true`.
|
||||
`palindrome("My age is 0, 0 si ega ym.")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(palindrome('My age is 0, 0 si ega ym.') === true);
|
||||
```
|
||||
|
||||
`palindrome("1 eye for of 1 eye.")` should return `false`.
|
||||
`palindrome("1 eye for of 1 eye.")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(palindrome('1 eye for of 1 eye.') === false);
|
||||
```
|
||||
|
||||
`palindrome("0_0 (: /-\ :) 0-0")` should return `true`.
|
||||
`palindrome("0_0 (: /-\ :) 0-0")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(palindrome('0_0 (: /- :) 0-0') === true);
|
||||
```
|
||||
|
||||
`palindrome("five|\_/|four")` should return `false`.
|
||||
`palindrome("five|\_/|four")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(palindrome('five|_/|four') === false);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a7f4d8f2483413a6ce226cac
|
||||
title: Roman Numeral Converter
|
||||
title: Conversor de Numerais Romanos
|
||||
challengeType: 5
|
||||
forumTopicId: 16044
|
||||
dashedName: roman-numeral-converter
|
||||
@ -8,163 +8,163 @@ dashedName: roman-numeral-converter
|
||||
|
||||
# --description--
|
||||
|
||||
Convert the given number into a roman numeral.
|
||||
Converta o número dado em um número romano.
|
||||
|
||||
All [roman numerals](http://www.mathsisfun.com/roman-numerals.html) answers should be provided in upper-case.
|
||||
Todas as respostas de [números romanos](http://www.mathsisfun.com/roman-numerals.html) devem ser fornecidas em maiúsculas.
|
||||
|
||||
# --hints--
|
||||
|
||||
`convertToRoman(2)` should return the string `II`.
|
||||
`convertToRoman(2)` deve retornar a string `II`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(2), 'II');
|
||||
```
|
||||
|
||||
`convertToRoman(3)` should return the string `III`.
|
||||
`convertToRoman(3)` deve retornar a string `III`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(3), 'III');
|
||||
```
|
||||
|
||||
`convertToRoman(4)` should return the string `IV`.
|
||||
`convertToRoman(4)` deve retornar a string `IV`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(4), 'IV');
|
||||
```
|
||||
|
||||
`convertToRoman(5)` should return the string `V`.
|
||||
`convertToRoman(5)` deve retornar a string `V`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(5), 'V');
|
||||
```
|
||||
|
||||
`convertToRoman(9)` should return the string `IX`.
|
||||
`convertToRoman(9)` deve retornar a string `IX`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(9), 'IX');
|
||||
```
|
||||
|
||||
`convertToRoman(12)` should return the string `XII`.
|
||||
`convertToRoman(12)` deve retornar a string `XII`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(12), 'XII');
|
||||
```
|
||||
|
||||
`convertToRoman(16)` should return the string `XVI`.
|
||||
`convertToRoman(16)` deve retornar a string `XVI`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(16), 'XVI');
|
||||
```
|
||||
|
||||
`convertToRoman(29)` should return the string `XXIX`.
|
||||
`convertToRoman(29)` deve retornar a string `XXIX`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(29), 'XXIX');
|
||||
```
|
||||
|
||||
`convertToRoman(44)` should return the string `XLIV`.
|
||||
`convertToRoman(44)` deve retornar a string `XLIV`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(44), 'XLIV');
|
||||
```
|
||||
|
||||
`convertToRoman(45)` should return the string `XLV`.
|
||||
`convertToRoman(45)` deve retornar a string `XLV`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(45), 'XLV');
|
||||
```
|
||||
|
||||
`convertToRoman(68)` should return the string `LXVIII`
|
||||
`convertToRoman(68)` deve retornar a string `LXVIII`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(68), 'LXVIII');
|
||||
```
|
||||
|
||||
`convertToRoman(83)` should return the string `LXXXIII`
|
||||
`convertToRoman(83)` deve retornar a string `LXXXIII`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(83), 'LXXXIII');
|
||||
```
|
||||
|
||||
`convertToRoman(97)` should return the string `XCVII`
|
||||
`convertToRoman(97)` deve retornar a string `XCVII`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(97), 'XCVII');
|
||||
```
|
||||
|
||||
`convertToRoman(99)` should return the string `XCIX`
|
||||
`convertToRoman(99)` deve retornar a string `XCIX`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(99), 'XCIX');
|
||||
```
|
||||
|
||||
`convertToRoman(400)` should return the string `CD`
|
||||
`convertToRoman(400)` deve retornar a string `CD`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(400), 'CD');
|
||||
```
|
||||
|
||||
`convertToRoman(500)` should return the string `D`
|
||||
`convertToRoman(500)` deve retornar a string `D`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(500), 'D');
|
||||
```
|
||||
|
||||
`convertToRoman(501)` should return the string `DI`
|
||||
`convertToRoman(501)` deve retornar a string `DI`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(501), 'DI');
|
||||
```
|
||||
|
||||
`convertToRoman(649)` should return the string `DCXLIX`
|
||||
`convertToRoman(649)` deve retornar a string `DCXLIX`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(649), 'DCXLIX');
|
||||
```
|
||||
|
||||
`convertToRoman(798)` should return the string `DCCXCVIII`
|
||||
`convertToRoman(798)` deve retornar a string `DCCXCVIII`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(798), 'DCCXCVIII');
|
||||
```
|
||||
|
||||
`convertToRoman(891)` should return the string `DCCCXCI`
|
||||
`convertToRoman(891)` deve retornar a string `DCCCXCI`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(891), 'DCCCXCI');
|
||||
```
|
||||
|
||||
`convertToRoman(1000)` should return the string `M`
|
||||
`convertToRoman(1000)` deve retornar a string `M`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(1000), 'M');
|
||||
```
|
||||
|
||||
`convertToRoman(1004)` should return the string `MIV`
|
||||
`convertToRoman(1004)` deve retornar a string `MIV`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(1004), 'MIV');
|
||||
```
|
||||
|
||||
`convertToRoman(1006)` should return the string `MVI`
|
||||
`convertToRoman(1006)` deve retornar a string `MVI`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(1006), 'MVI');
|
||||
```
|
||||
|
||||
`convertToRoman(1023)` should return the string `MXXIII`
|
||||
`convertToRoman(1023)` deve retornar a string `MXXIII`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(1023), 'MXXIII');
|
||||
```
|
||||
|
||||
`convertToRoman(2014)` should return the string `MMXIV`
|
||||
`convertToRoman(2014)` deve retornar a string `MMXIV`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(2014), 'MMXIV');
|
||||
```
|
||||
|
||||
`convertToRoman(3999)` should return the string `MMMCMXCIX`
|
||||
`convertToRoman(3999)` deve retornar a string `MMMCMXCIX`
|
||||
|
||||
```js
|
||||
assert.deepEqual(convertToRoman(3999), 'MMMCMXCIX');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: aff0395860f5d3034dc0bfc9
|
||||
title: Telephone Number Validator
|
||||
title: Validador de Número Telefônico
|
||||
challengeType: 5
|
||||
forumTopicId: 16090
|
||||
dashedName: telephone-number-validator
|
||||
@ -8,179 +8,179 @@ dashedName: telephone-number-validator
|
||||
|
||||
# --description--
|
||||
|
||||
Return `true` if the passed string looks like a valid US phone number.
|
||||
Retorna `true` se a string fornecida se parece com um número telefônico dos Estados Unidos válido.
|
||||
|
||||
The user may fill out the form field any way they choose as long as it has the format of a valid US number. The following are examples of valid formats for US numbers (refer to the tests below for other variants):
|
||||
O usuário pode preencher o campo do formulário de qualquer maneira que escolher contanto que tenha o formato de um número válido dos EUA. Os seguintes são exemplos de formatos válidos para números nos EUA (consulte os testes abaixo para outras variantes):
|
||||
|
||||
<blockquote>555-555-5555<br>(555)555-5555<br>(555) 555-5555<br>555 555 5555<br>5555555555<br>1 555 555 5555</blockquote>
|
||||
|
||||
For this challenge you will be presented with a string such as `800-692-7753` or `8oo-six427676;laskdjf`. Your job is to validate or reject the US phone number based on any combination of the formats provided above. The area code is required. If the country code is provided, you must confirm that the country code is `1`. Return `true` if the string is a valid US phone number; otherwise return `false`.
|
||||
Para este desafio, você vai receber uma string como `800-692-7753` ou `8oo-six427676;laskdjf`. Seu trabalho é validar ou rejeitar o número de telefone dos EUA com base em qualquer combinação dos formatos fornecidos acima. O código de área é obrigatório. Se o código do país é fornecido, você deve confirmar que o código do país é `1`. Retorne `true` se a seqüência de caracteres for um número válido de telefone dos EUA; caso contrário, retorne `false`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`telephoneCheck("555-555-5555")` should return a boolean.
|
||||
`telephoneCheck("555-555-5555")` deve retornar um boolean.
|
||||
|
||||
```js
|
||||
assert(typeof telephoneCheck('555-555-5555') === 'boolean');
|
||||
```
|
||||
|
||||
`telephoneCheck("1 555-555-5555")` should return `true`.
|
||||
`telephoneCheck("1 555-555-5555")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('1 555-555-5555') === true);
|
||||
```
|
||||
|
||||
`telephoneCheck("1 (555) 555-5555")` should return `true`.
|
||||
`telephoneCheck("1 (555) 555-5555")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('1 (555) 555-5555') === true);
|
||||
```
|
||||
|
||||
`telephoneCheck("5555555555")` should return `true`.
|
||||
`telephoneCheck("5555555555")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('5555555555') === true);
|
||||
```
|
||||
|
||||
`telephoneCheck("555-555-5555")` should return `true`.
|
||||
`telephoneCheck("555-555-5555")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('555-555-5555') === true);
|
||||
```
|
||||
|
||||
`telephoneCheck("(555)555-5555")` should return `true`.
|
||||
`telephoneCheck("(555)555-5555")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('(555)555-5555') === true);
|
||||
```
|
||||
|
||||
`telephoneCheck("1(555)555-5555")` should return `true`.
|
||||
`telephoneCheck("1(555)555-5555")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('1(555)555-5555') === true);
|
||||
```
|
||||
|
||||
`telephoneCheck("555-5555")` should return `false`.
|
||||
`telephoneCheck("555-5555")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('555-5555') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("5555555")` should return `false`.
|
||||
`telephoneCheck("5555555")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('5555555') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("1 555)555-5555")` should return `false`.
|
||||
`telephoneCheck("1 555)555-5555")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('1 555)555-5555') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("1 555 555 5555")` should return `true`.
|
||||
`telephoneCheck("1 555 555 5555")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('1 555 555 5555') === true);
|
||||
```
|
||||
|
||||
`telephoneCheck("1 456 789 4444")` should return `true`.
|
||||
`telephoneCheck("1 456 789 4444")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('1 456 789 4444') === true);
|
||||
```
|
||||
|
||||
`telephoneCheck("123**&!!asdf#")` should return `false`.
|
||||
`telephoneCheck("123**&!!asdf#")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('123**&!!asdf#') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("55555555")` should return `false`.
|
||||
`telephoneCheck("55555555")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('55555555') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("(6054756961)")` should return `false`.
|
||||
`telephoneCheck("(6054756961)")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('(6054756961)') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("2 (757) 622-7382")` should return `false`.
|
||||
`telephoneCheck("2 (757) 622-7382")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('2 (757) 622-7382') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("0 (757) 622-7382")` should return `false`.
|
||||
`telephoneCheck("0 (757) 622-7382")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('0 (757) 622-7382') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("-1 (757) 622-7382")` should return `false`.
|
||||
`telephoneCheck("-1 (757) 622-7382")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('-1 (757) 622-7382') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("2 757 622-7382")` should return `false`.
|
||||
`telephoneCheck("2 757 622-7382")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('2 757 622-7382') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("10 (757) 622-7382")` should return `false`.
|
||||
`telephoneCheck("10 (757) 622-7382")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('10 (757) 622-7382') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("27576227382")` should return `false`.
|
||||
`telephoneCheck("27576227382")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('27576227382') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("(275)76227382")` should return `false`.
|
||||
`telephoneCheck("(275)76227382")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('(275)76227382') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("2(757)6227382")` should return `false`.
|
||||
`telephoneCheck("2(757)6227382")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('2(757)6227382') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("2(757)622-7382")` should return `false`.
|
||||
`telephoneCheck("2(757)622-7382")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('2(757)622-7382') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("555)-555-5555")` should return `false`.
|
||||
`telephoneCheck("555)-555-5555")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('555)-555-5555') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("(555-555-5555")` should return `false`.
|
||||
`telephoneCheck("(555-555-5555")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('(555-555-5555') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("(555)5(55?)-5555")` should return `false`.
|
||||
`telephoneCheck("(555)5(55?)-5555")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('(555)5(55?)-5555') === false);
|
||||
```
|
||||
|
||||
`telephoneCheck("55 55-55-555-5")` should return `false`.
|
||||
`telephoneCheck("55 55-55-555-5")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(telephoneCheck('55 55-55-555-5') === false);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db1367417b2b2512b87
|
||||
title: Add Methods After Inheritance
|
||||
title: Adicionar Métodos Após Herança
|
||||
challengeType: 1
|
||||
forumTopicId: 301315
|
||||
dashedName: add-methods-after-inheritance
|
||||
@ -8,9 +8,9 @@ dashedName: add-methods-after-inheritance
|
||||
|
||||
# --description--
|
||||
|
||||
A constructor function that inherits its `prototype` object from a supertype constructor function can still have its own methods in addition to inherited methods.
|
||||
Uma função construtora, ou simplesmente construtor, que herda seu objeto de `protótipo` de uma função construtora de supertipo, além dos métodos herdados, ainda poderá ter seus próprios métodos.
|
||||
|
||||
For example, `Bird` is a constructor that inherits its `prototype` from `Animal`:
|
||||
Por exemplo, `Bird` é um construtor que herda seu `protótipo` de `Animal`:
|
||||
|
||||
```js
|
||||
function Animal() { }
|
||||
@ -22,7 +22,7 @@ Bird.prototype = Object.create(Animal.prototype);
|
||||
Bird.prototype.constructor = Bird;
|
||||
```
|
||||
|
||||
In addition to what is inherited from `Animal`, you want to add behavior that is unique to `Bird` objects. Here, `Bird` will get a `fly()` function. Functions are added to `Bird's` `prototype` the same way as any constructor function:
|
||||
Como adicional do que é herdado da classe `Animal`, você deseja adicionar o comportamento que é único de objetos `Bird`. Aqui, `Bird` irá definir a função `fly()`. As funções são adicionadas ao `protótipo` `Bird` da mesma forma que qualquer função construtora:
|
||||
|
||||
```js
|
||||
Bird.prototype.fly = function() {
|
||||
@ -30,7 +30,7 @@ Bird.prototype.fly = function() {
|
||||
};
|
||||
```
|
||||
|
||||
Now instances of `Bird` will have both `eat()` and `fly()` methods:
|
||||
Agora as instâncias de `Bird` terão ambos os métodos, `eat()` e `fly()`:
|
||||
|
||||
```js
|
||||
let duck = new Bird();
|
||||
@ -38,45 +38,45 @@ duck.eat();
|
||||
duck.fly();
|
||||
```
|
||||
|
||||
`duck.eat()` would display the string `nom nom nom` in the console, and `duck.fly()` would display the string `I'm flying!`.
|
||||
`duck.eat()` exibe no console a string `nom nom nom`, e `duck.fly()` mostra a string `I'm flying!`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add all necessary code so the `Dog` object inherits from `Animal` and the `Dog`'s `prototype` constructor is set to `Dog`. Then add a `bark()` method to the `Dog` object so that `beagle` can both `eat()` and `bark()`. The `bark()` method should print `Woof!` to the console.
|
||||
Adiciona todos os códigos necessários para que o objeto `Dog` herde de `Animal` e o `protótipo` de construtor de `Dog` está definido para `Dog`. Então adiciona o método `bark()` para o objeto `Dog` para que um `beagle` possa `eat()` e `bark()`. O método `bark()` deveria imprimir no console a string: `Woof!`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Animal` should not respond to the `bark()` method.
|
||||
`Animal` não deve possuir o método `bark()`.
|
||||
|
||||
```js
|
||||
assert(typeof Animal.prototype.bark == 'undefined');
|
||||
```
|
||||
|
||||
`Dog` should inherit the `eat()` method from `Animal`.
|
||||
`Dog` deve herdar o método `eat()` de `Animal`.
|
||||
|
||||
```js
|
||||
assert(typeof Dog.prototype.eat == 'function');
|
||||
```
|
||||
|
||||
The `Dog` prototype should have a `bark()` method.
|
||||
O protótipo de `Dog` deve ter o método `bark()`.
|
||||
|
||||
```js
|
||||
assert('bark' in Dog.prototype);
|
||||
```
|
||||
|
||||
`beagle` should be an `instanceof` `Animal`.
|
||||
`beagle` deve ser uma `instância` de `Animal`.
|
||||
|
||||
```js
|
||||
assert(beagle instanceof Animal);
|
||||
```
|
||||
|
||||
The constructor for `beagle` should be set to `Dog`.
|
||||
O construtor para `beagle` deve ser definido para `Dog`.
|
||||
|
||||
```js
|
||||
assert(beagle.constructor === Dog);
|
||||
```
|
||||
|
||||
`beagle.eat()` should log the string `nom nom nom`
|
||||
`beagle.eat()` deve mostrar no console a string `nom nom nom`
|
||||
|
||||
```js
|
||||
console.log = function (msg) {
|
||||
@ -85,7 +85,7 @@ console.log = function (msg) {
|
||||
assert.throws(() => beagle.eat(), 'nom nom nom');
|
||||
```
|
||||
|
||||
`beagle.bark()` should log the string `Woof!`
|
||||
`beagle.bark()` deve mostrar no console a string `nom nom nom`
|
||||
|
||||
```js
|
||||
console.log = function (msg) {
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7daf367417b2b2512b7f
|
||||
title: Change the Prototype to a New Object
|
||||
title: Mudar o Protótipo para um Novo Objeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301316
|
||||
dashedName: change-the-prototype-to-a-new-object
|
||||
@ -8,13 +8,13 @@ dashedName: change-the-prototype-to-a-new-object
|
||||
|
||||
# --description--
|
||||
|
||||
Up until now you have been adding properties to the `prototype` individually:
|
||||
Até o momento, você tem adicionado propriedades para cada `protótipo` individualmente:
|
||||
|
||||
```js
|
||||
Bird.prototype.numLegs = 2;
|
||||
```
|
||||
|
||||
This becomes tedious after more than a few properties.
|
||||
Isto se torna entediante após mais do que algumas propriedades.
|
||||
|
||||
```js
|
||||
Bird.prototype.eat = function() {
|
||||
@ -26,7 +26,7 @@ Bird.prototype.describe = function() {
|
||||
}
|
||||
```
|
||||
|
||||
A more efficient way is to set the `prototype` to a new object that already contains the properties. This way, the properties are added all at once:
|
||||
Uma forma mais eficiente é definir o `protótipo` para um novo objeto que já possui as propriedades. Dessa maneira, as propriedades são adicionadas todas de uma vez:
|
||||
|
||||
```js
|
||||
Bird.prototype = {
|
||||
@ -42,29 +42,29 @@ Bird.prototype = {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the property `numLegs` and the two methods `eat()` and `describe()` to the `prototype` of `Dog` by setting the `prototype` to a new object.
|
||||
Adiciona a propriedade `numLegs` e os dois métodos `eat()` e `describe()` para o `protótipo` de `Dog` definindo o `protótipo` para um novo objeto.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Dog.prototype` should be set to a new object.
|
||||
`Dog.prototype` deve ser definido para um novo objeto.
|
||||
|
||||
```js
|
||||
assert(/Dog\.prototype\s*?=\s*?{/.test(code));
|
||||
```
|
||||
|
||||
`Dog.prototype` should have the property `numLegs`.
|
||||
`Dog.prototype` deve ter a propriedade `numLegs`.
|
||||
|
||||
```js
|
||||
assert(Dog.prototype.numLegs !== undefined);
|
||||
```
|
||||
|
||||
`Dog.prototype` should have the method `eat()`.
|
||||
`Dog.prototype` deve ter o método `eat()`.
|
||||
|
||||
```js
|
||||
assert(typeof Dog.prototype.eat === 'function');
|
||||
```
|
||||
|
||||
`Dog.prototype` should have the method `describe()`.
|
||||
`Dog.prototype` deve ter o método `describe()`.
|
||||
|
||||
```js
|
||||
assert(typeof Dog.prototype.describe === 'function');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dac367417b2b2512b73
|
||||
title: Create a Basic JavaScript Object
|
||||
title: Crie um Objeto JavaScript Básico
|
||||
challengeType: 1
|
||||
forumTopicId: 301317
|
||||
dashedName: create-a-basic-javascript-object
|
||||
@ -8,13 +8,13 @@ dashedName: create-a-basic-javascript-object
|
||||
|
||||
# --description--
|
||||
|
||||
Think about things people see every day, like cars, shops, and birds. These are all <dfn>objects</dfn>: tangible things people can observe and interact with.
|
||||
Pense sobre as coisas que as pessoas veem todos os dias, como carros, lojas e pássaros. Tudo isso são <dfn>objetos</dfn>: coisas tangíveis com que pessoas podem observar e interagir.
|
||||
|
||||
What are some qualities of these objects? A car has wheels. Shops sell items. Birds have wings.
|
||||
Quais são algumas qualidades destes objetos? Um carro possui rodas. Lojas vendem itens. Pássaros possuem asas.
|
||||
|
||||
These qualities, or <dfn>properties</dfn>, define what makes up an object. Note that similar objects share the same properties, but may have different values for those properties. For example, all cars have wheels, but not all cars have the same number of wheels.
|
||||
Estas qualidades, ou <dfn>propriedades</dfn>, definem o que faz um objeto. Note que objetos similares compartilham de propriedades iguais, mas podem ter diferentes valores para estas propriedades. Por exemplo, todos os carros possuem rodas, mas nem todos os carros possuem o mesmo número de rodas.
|
||||
|
||||
Objects in JavaScript are used to model real-world objects, giving them properties and behavior just like their real-world counterparts. Here's an example using these concepts to create a `duck` object:
|
||||
Objetos em JavaScript são utilizados como modelos de objetos do mundo real, dando a eles propriedades e comportamentos assim como se fossem análogos ao mundo real. Aqui está um exemplo utilizando estes conceitos para a criação de um objeto `duck`:
|
||||
|
||||
```js
|
||||
let duck = {
|
||||
@ -23,27 +23,27 @@ let duck = {
|
||||
};
|
||||
```
|
||||
|
||||
This `duck` object has two property/value pairs: a `name` of `Aflac` and a `numLegs` of 2.
|
||||
O objeto `duck` possui dois pares de propriedades/valores: um `name` sendo `Aflac` e um `numLegs` sendo 2.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a `dog` object with `name` and `numLegs` properties, and set them to a string and a number, respectively.
|
||||
Cria um objeto `dog` com as propriedades `name` e `numLegs`, e definem eles como sendo do tipo string e numérico, respectivamente.
|
||||
|
||||
# --hints--
|
||||
|
||||
`dog` should be an object.
|
||||
`dog` deve ser um objeto.
|
||||
|
||||
```js
|
||||
assert(typeof dog === 'object');
|
||||
```
|
||||
|
||||
`dog` should have a `name` property set to a string.
|
||||
`dog` deve ter uma propriedade `name` definido para uma string.
|
||||
|
||||
```js
|
||||
assert(typeof dog.name === 'string');
|
||||
```
|
||||
|
||||
`dog` should have a `numLegs` property set to a number.
|
||||
`dog` deve ter uma propriedade `numLeggs` definido para um número.
|
||||
|
||||
```js
|
||||
assert(typeof dog.numLegs === 'number');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dad367417b2b2512b75
|
||||
title: Create a Method on an Object
|
||||
title: Cria um Método em um Objeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301318
|
||||
dashedName: create-a-method-on-an-object
|
||||
@ -8,9 +8,9 @@ dashedName: create-a-method-on-an-object
|
||||
|
||||
# --description--
|
||||
|
||||
Objects can have a special type of property, called a <dfn>method</dfn>.
|
||||
Objetos podem ter um tipo especial de propriedade, chamado de <dfn>método</dfn>.
|
||||
|
||||
Methods are properties that are functions. This adds different behavior to an object. Here is the `duck` example with a method:
|
||||
Métodos e propriedades são funções. Isso adiciona diferentes comportamentos para um objeto. Aqui está o exemplo `duck` com um método:
|
||||
|
||||
```js
|
||||
let duck = {
|
||||
@ -21,21 +21,21 @@ let duck = {
|
||||
duck.sayName();
|
||||
```
|
||||
|
||||
The example adds the `sayName` method, which is a function that returns a sentence giving the name of the `duck`. Notice that the method accessed the `name` property in the return statement using `duck.name`. The next challenge will cover another way to do this.
|
||||
O exemplo adiciona o método `sayName`, que é uma função responsável por retornar uma frase contendo o nome do `duck`. Note que o método acessou a propriedade `name` na declaração de retorno usando `duck.name`. O próximo desafio irá mostrar outra forma de fazer isso.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Using the `dog` object, give it a method called `sayLegs`. The method should return the sentence `This dog has 4 legs.`
|
||||
Usando o objeto `dog`, de a ele um método chamado `sayLegs`. O método deve retornar a frase `This dog has 4 legs. (Este cachorro possui 4 pernas.)`
|
||||
|
||||
# --hints--
|
||||
|
||||
`dog.sayLegs()` should be a function.
|
||||
`dog.sayLegs()` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof dog.sayLegs === 'function');
|
||||
```
|
||||
|
||||
`dog.sayLegs()` should return the given string - note that punctuation and spacing matter.
|
||||
`dog.sayLegs()` deve retornar a string definida - note que pontuação e espaçamento importa.
|
||||
|
||||
```js
|
||||
assert(dog.sayLegs() === 'This dog has 4 legs.');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dad367417b2b2512b77
|
||||
title: Define a Constructor Function
|
||||
title: Define uma Função Construtora
|
||||
challengeType: 1
|
||||
forumTopicId: 16804
|
||||
dashedName: define-a-constructor-function
|
||||
@ -8,9 +8,9 @@ dashedName: define-a-constructor-function
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Constructors</dfn> are functions that create new objects. They define properties and behaviors that will belong to the new object. Think of them as a blueprint for the creation of new objects.
|
||||
<dfn>Construtores</dfn> são funções que criam novos objetos. Eles definem propriedades e comportamentos que pertencerão ao novo objeto. Pense neles como uma planta para a criação de novos objetos.
|
||||
|
||||
Here is an example of a constructor:
|
||||
Aqui está um exemplo de construtor:
|
||||
|
||||
```js
|
||||
function Bird() {
|
||||
@ -20,29 +20,29 @@ function Bird() {
|
||||
}
|
||||
```
|
||||
|
||||
This constructor defines a `Bird` object with properties `name`, `color`, and `numLegs` set to Albert, blue, and 2, respectively. Constructors follow a few conventions:
|
||||
O construtor define um objeto `Bird` com propriedades `name`, `color`, e `numLegs` definidos como Albert, blue e 2, respectivamente. Construtores seguem algumas convenções:
|
||||
|
||||
<ul><li>Constructors are defined with a capitalized name to distinguish them from other functions that are not <code>constructors</code>.</li><li>Constructors use the keyword <code>this</code> to set properties of the object they will create. Inside the constructor, <code>this</code> refers to the new object it will create.</li><li>Constructors define properties and behaviors instead of returning a value as other functions might.</li></ul>
|
||||
<ul><li>Construtores são definidos com a primeira letra do nome maiúscula para distinguir eles de outras funções que não são <code>construtores</code>.</li><li>Construtores usam a palavra-chave <code>this</code> para definir as propriedades do objeto que eles irão criar. Dentro do construtor, <code>this</code> referencia para um novo objeto quer irá ser criado.</li><li>Construtores definem propriedades e comportamentos em vez de retornar valores como outras funções podem fazer.</li></ul>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a constructor, `Dog`, with properties `name`, `color`, and `numLegs` that are set to a string, a string, and a number, respectively.
|
||||
Crie um construtor, `Dog`, com as propriedades `name`, `color` e `numLegs` que são definidos como string, string e número, respectivamente.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Dog` should have a `name` property set to a string.
|
||||
`Dog` deve term uma propriedade `name` definida como uma string.
|
||||
|
||||
```js
|
||||
assert(typeof new Dog().name === 'string');
|
||||
```
|
||||
|
||||
`Dog` should have a `color` property set to a string.
|
||||
`Dog` deve ter a propriedade `color` definida como uma string.
|
||||
|
||||
```js
|
||||
assert(typeof new Dog().color === 'string');
|
||||
```
|
||||
|
||||
`Dog` should have a `numLegs` property set to a number.
|
||||
`Dog` deve ter a propriedade `numLegs` definida como um número.
|
||||
|
||||
```js
|
||||
assert(typeof new Dog().numLegs === 'number');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dae367417b2b2512b79
|
||||
title: Extend Constructors to Receive Arguments
|
||||
title: Estenda Construtores para Receber Argumentos
|
||||
challengeType: 1
|
||||
forumTopicId: 18235
|
||||
dashedName: extend-constructors-to-receive-arguments
|
||||
@ -8,7 +8,7 @@ dashedName: extend-constructors-to-receive-arguments
|
||||
|
||||
# --description--
|
||||
|
||||
The `Bird` and `Dog` constructors from the last challenge worked well. However, notice that all `Birds` that are created with the `Bird` constructor are automatically named Albert, are blue in color, and have two legs. What if you want birds with different values for name and color? It's possible to change the properties of each bird manually but that would be a lot of work:
|
||||
Os construtores `Bird` e `Dog` do último desafio funcionaram bem. No entanto, note que todos os `Birds` que são criados com o construtor `Bird` são automaticamente nomeados Albeart, são da cor azul e possuem duas pernas. E se você deseja pássaros com diferentes valores para seus nomes e cores? É possível alterar estas propriedades de cada pássaro manualmente, mas isso daria bastante trabalho:
|
||||
|
||||
```js
|
||||
let swan = new Bird();
|
||||
@ -16,7 +16,7 @@ swan.name = "Carlos";
|
||||
swan.color = "white";
|
||||
```
|
||||
|
||||
Suppose you were writing a program to keep track of hundreds or even thousands of different birds in an aviary. It would take a lot of time to create all the birds, then change the properties to different values for every one. To more easily create different `Bird` objects, you can design your Bird constructor to accept parameters:
|
||||
Suponha que você está escrevendo um programa para registrar centenas ou até milhares de diferentes pássaros em um aviário. Seria necessário muito tempo para criar todos estes pássaros, e então alterar as propriedades para os diferentes valores de cada um. Para criar diferentes objetos `Bird` de forma mais fácil, você pode projetar o construtor de Bird para aceitar parâmetros:
|
||||
|
||||
```js
|
||||
function Bird(name, color) {
|
||||
@ -26,7 +26,7 @@ function Bird(name, color) {
|
||||
}
|
||||
```
|
||||
|
||||
Then pass in the values as arguments to define each unique bird into the `Bird` constructor: `let cardinal = new Bird("Bruce", "red");` This gives a new instance of `Bird` with `name` and `color` properties set to `Bruce` and `red`, respectively. The `numLegs` property is still set to 2. The `cardinal` has these properties:
|
||||
Em seguida, passe os valores como argumentos para definir cada pássaro único no construtor `Bird`: ` let cardinal = new Bird("Bruce","red");` Isso dará uma nova instância de `Bird` com as propriedades `name` e `color` definidas como `Bruce` e `red`, respectivamente. A propriedade `numLegs` ainda está definida como 2. O `cardinal` possui três propriedades:
|
||||
|
||||
```js
|
||||
cardinal.name
|
||||
@ -34,33 +34,33 @@ cardinal.color
|
||||
cardinal.numLegs
|
||||
```
|
||||
|
||||
The constructor is more flexible. It's now possible to define the properties for each `Bird` at the time it is created, which is one way that JavaScript constructors are so useful. They group objects together based on shared characteristics and behavior and define a blueprint that automates their creation.
|
||||
O construtor é mais flexível. Agora é possível definir as propriedades de cada `Bird` ao mesmo tempo em que são criados, o que é uma grande utilidade dos construtores JavaScript. Eles agrupam junto objetos baseados em características e comportamentos compartilhados e definem uma planta que automatiza a criação deles.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create another `Dog` constructor. This time, set it up to take the parameters `name` and `color`, and have the property `numLegs` fixed at 4. Then create a new `Dog` saved in a variable `terrier`. Pass it two strings as arguments for the `name` and `color` properties.
|
||||
Crie outro construtor `Dog`. Desta vez, defina o construtor para receber os parâmetros `name` e `color`, e que tenham a propriedade `numLegs` fixada em 4. Em seguida, crie um novo `Dog` salvo na variável `terrier`. Passe duas strings como argumentos para as propriedades `name` e `color`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Dog` should receive an argument for `name`.
|
||||
`Dog` deve receber um argumento para `name`.
|
||||
|
||||
```js
|
||||
assert(new Dog('Clifford').name === 'Clifford');
|
||||
```
|
||||
|
||||
`Dog` should receive an argument for `color`.
|
||||
`Dog` deve receber um argumento para `color`.
|
||||
|
||||
```js
|
||||
assert(new Dog('Clifford', 'yellow').color === 'yellow');
|
||||
```
|
||||
|
||||
`Dog` should have property `numLegs` set to 4.
|
||||
`Dog` deve ter a propriedade `numLegs` definido como 4.
|
||||
|
||||
```js
|
||||
assert(new Dog('Clifford').numLegs === 4);
|
||||
```
|
||||
|
||||
`terrier` should be created using the `Dog` constructor.
|
||||
`terrier` deve ser criado usando o construtor `Dog`.
|
||||
|
||||
```js
|
||||
assert(terrier instanceof Dog);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db0367417b2b2512b84
|
||||
title: Inherit Behaviors from a Supertype
|
||||
title: Herde Comportamentos de um Supertipo
|
||||
challengeType: 1
|
||||
forumTopicId: 301319
|
||||
dashedName: inherit-behaviors-from-a-supertype
|
||||
@ -8,7 +8,7 @@ dashedName: inherit-behaviors-from-a-supertype
|
||||
|
||||
# --description--
|
||||
|
||||
In the previous challenge, you created a `supertype` called `Animal` that defined behaviors shared by all animals:
|
||||
No desafio anterior, você criou um `supertipo` chamado `Animal` que define os comportamentos compartilhados por todos os animais:
|
||||
|
||||
```js
|
||||
function Animal() { }
|
||||
@ -17,46 +17,46 @@ Animal.prototype.eat = function() {
|
||||
};
|
||||
```
|
||||
|
||||
This and the next challenge will cover how to reuse the methods of `Animal` inside `Bird` and `Dog` without defining them again. It uses a technique called inheritance. This challenge covers the first step: make an instance of the `supertype` (or parent). You already know one way to create an instance of `Animal` using the `new` operator:
|
||||
Este e o próximo desafio irá abordar como reutilizar métodos de `Animal` dentro de `Bird` e `Dog` sem ter de definir os métodos novamente. Ele utiliza uma técnica chamada herança. Este desafio cobrirá o primeiro passo: fazer uma instância do `supertipo` (ou parente). Você já sabe uma forma de criar instâncias de `Animal` utilizando o operador `new`:
|
||||
|
||||
```js
|
||||
let animal = new Animal();
|
||||
```
|
||||
|
||||
There are some disadvantages when using this syntax for inheritance, which are too complex for the scope of this challenge. Instead, here's an alternative approach without those disadvantages:
|
||||
Há algumas desvantagens quando utilizamos essa sintaxe para herança, que são muito complexas para o escopo deste desafio. Em vez disso, aqui está uma abordagem alternativa sem essas desvantagens:
|
||||
|
||||
```js
|
||||
let animal = Object.create(Animal.prototype);
|
||||
```
|
||||
|
||||
`Object.create(obj)` creates a new object, and sets `obj` as the new object's `prototype`. Recall that the `prototype` is like the "recipe" for creating an object. By setting the `prototype` of `animal` to be the `prototype` of `Animal`, you are effectively giving the `animal` instance the same "recipe" as any other instance of `Animal`.
|
||||
`Object.create(obj)` cria um novo objeto, e define `obj` como o novo `protótipo` do objeto. Lembre-se que o `protótipo` é como uma "receita" para criar um objeto. Ao definir o `prototype` de `animal` para ser um `prototype` de `Animal`, você está efetivamente dando a instância `animal` a mesma "receita" de qualquer outra instância de `Animal`.
|
||||
|
||||
```js
|
||||
animal.eat();
|
||||
animal instanceof Animal;
|
||||
```
|
||||
|
||||
The `instanceof` method here would return `true`.
|
||||
O método `instanceof` aqui irá retornar `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use `Object.create` to make two instances of `Animal` named `duck` and `beagle`.
|
||||
Utilize `Object.create` para fazer duas instâncias de `Animal` nomeados `duck` e `beagle`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `duck` variable should be defined.
|
||||
A variável `duck` deve ser definida.
|
||||
|
||||
```js
|
||||
assert(typeof duck !== 'undefined');
|
||||
```
|
||||
|
||||
The `beagle` variable should be defined.
|
||||
A variável `beagle` deve ser definida.
|
||||
|
||||
```js
|
||||
assert(typeof beagle !== 'undefined');
|
||||
```
|
||||
|
||||
The `duck` variable should be initialised with `Object.create`.
|
||||
A variável `duck` deve ser inicializada com `Object.create`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -66,7 +66,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `beagle` variable should be initialised with `Object.create`.
|
||||
A variável `beagle` deve ser inicializada com `Object.create`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -76,13 +76,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`duck` should have a `prototype` of `Animal`.
|
||||
`duck` deve ter o `protótipo` de `Animal`.
|
||||
|
||||
```js
|
||||
assert(duck instanceof Animal);
|
||||
```
|
||||
|
||||
`beagle` should have a `prototype` of `Animal`.
|
||||
`beagle` deve ter o `protótipo` de `Animal`.
|
||||
|
||||
```js
|
||||
assert(beagle instanceof Animal);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7daf367417b2b2512b7d
|
||||
title: Iterate Over All Properties
|
||||
title: Itere Sobre Todas as Propriedades
|
||||
challengeType: 1
|
||||
forumTopicId: 301320
|
||||
dashedName: iterate-over-all-properties
|
||||
@ -8,7 +8,7 @@ dashedName: iterate-over-all-properties
|
||||
|
||||
# --description--
|
||||
|
||||
You have now seen two kinds of properties: <dfn>own properties</dfn> and `prototype` properties. Own properties are defined directly on the object instance itself. And `prototype` properties are defined on the `prototype`.
|
||||
Até agora você já viu dois tipos de propriedades: as propriedades <dfn>own properties</dfn> e `prototype`. Propriedades próprias (ou Own properties) são definidas diretamente na própria instância do objeto. E as propriedades `prototype` são definidas no `prototype`.
|
||||
|
||||
```js
|
||||
function Bird(name) {
|
||||
@ -20,7 +20,7 @@ Bird.prototype.numLegs = 2; // prototype property
|
||||
let duck = new Bird("Donald");
|
||||
```
|
||||
|
||||
Here is how you add `duck`'s own properties to the array `ownProps` and `prototype` properties to the array `prototypeProps`:
|
||||
Aqui está como você adiciona own properties `duck` para o array `ownProps` e propriedades `prototype` para o array `prototypeProps`:
|
||||
|
||||
```js
|
||||
let ownProps = [];
|
||||
@ -38,27 +38,27 @@ console.log(ownProps);
|
||||
console.log(prototypeProps);
|
||||
```
|
||||
|
||||
`console.log(ownProps)` would display `["name"]` in the console, and `console.log(prototypeProps)` would display `["numLegs"]`.
|
||||
`console.log(ownProps)` deve exibir no console `["name"]`, e `console.log(prototypeProps)` exibirá no console `["numLegs"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add all of the own properties of `beagle` to the array `ownProps`. Add all of the `prototype` properties of `Dog` to the array `prototypeProps`.
|
||||
Adicione todas as propriedades próprias de `beagle` para o array `ownProps`. Adicione todas as propriedades `prototype` de `Dog` para o array `prototypeProps`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `ownProps` array should only contain `name`.
|
||||
O array `ownProps` deve conter apenas `name`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(ownProps, ['name']);
|
||||
```
|
||||
|
||||
The `prototypeProps` array should only contain `numLegs`.
|
||||
O array `prototypeProps` deve conter apenas `numLegs`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(prototypeProps, ['numLegs']);
|
||||
```
|
||||
|
||||
You should solve this challenge without using the built in method `Object.keys()`.
|
||||
Você deve resolver este desafio sem utilizar o método nativo `Object.keys()`.
|
||||
|
||||
```js
|
||||
assert(!/\Object.keys/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dad367417b2b2512b76
|
||||
title: Make Code More Reusable with the this Keyword
|
||||
title: Faça Código Mais Reutilizável com a Palavra-Chave this
|
||||
challengeType: 1
|
||||
forumTopicId: 301321
|
||||
dashedName: make-code-more-reusable-with-the-this-keyword
|
||||
@ -8,15 +8,15 @@ dashedName: make-code-more-reusable-with-the-this-keyword
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge introduced a method to the `duck` object. It used `duck.name` dot notation to access the value for the `name` property within the return statement:
|
||||
O último desafio introduziu um método ao objeto `duck`. Ele utiliza ponto notação (`duck.name`) para acessar o valor da propriedade `name` dentro da declaração de retorno:
|
||||
|
||||
```js
|
||||
sayName: function() {return "The name of this duck is " + duck.name + ".";}
|
||||
```
|
||||
|
||||
While this is a valid way to access the object's property, there is a pitfall here. If the variable name changes, any code referencing the original name would need to be updated as well. In a short object definition, it isn't a problem, but if an object has many references to its properties there is a greater chance for error.
|
||||
Enquanto isso é uma forma válida de acessar a propriedade do objeto, tem uma armadilha aqui. Se o nome da variável mudar, qualquer código referenciando o nome original seria necessário ser atualizado também. Em uma definição curta de objeto, isso não é um problema, mas se um objeto possui muitas referencias para suas propriedades, há uma chance maior de erro.
|
||||
|
||||
A way to avoid these issues is with the `this` keyword:
|
||||
Uma forma para evitar estes problemas é utilizar a palavra-chave `this`:
|
||||
|
||||
```js
|
||||
let duck = {
|
||||
@ -26,21 +26,21 @@ let duck = {
|
||||
};
|
||||
```
|
||||
|
||||
`this` is a deep topic, and the above example is only one way to use it. In the current context, `this` refers to the object that the method is associated with: `duck`. If the object's name is changed to `mallard`, it is not necessary to find all the references to `duck` in the code. It makes the code reusable and easier to read.
|
||||
`this` é um tópico bem extenso e o exemplo acima é apenas uma forma de utilizá-lo. No contexto atual, `this` refere-se ao objeto que o método está associado à: `duck`. Se o nome do objeto é alterado para `mallard`, não é necessariamente para encontrar todas as referencias para `duck` no código. Isso torna o código reutilizável e legível.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the `dog.sayLegs` method to remove any references to `dog`. Use the `duck` example for guidance.
|
||||
Modifique o método `dog.sayLegs` para remover qualquer referencia para `dog`. Utilize o exemplo `duck` como guia.
|
||||
|
||||
# --hints--
|
||||
|
||||
`dog.sayLegs()` should return the given string.
|
||||
`dog.sayLegs()` deve retornar a string definida.
|
||||
|
||||
```js
|
||||
assert(dog.sayLegs() === 'This dog has 4 legs.');
|
||||
```
|
||||
|
||||
Your code should use the `this` keyword to access the `numLegs` property of `dog`.
|
||||
Seu código deve utilizar a palavra-chave `this` para acessar a propriedade `numLegs` de `dog`.
|
||||
|
||||
```js
|
||||
assert(code.match(/this\.numLegs/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db1367417b2b2512b88
|
||||
title: Override Inherited Methods
|
||||
title: Sobrescreva Métodos Herdados
|
||||
challengeType: 1
|
||||
forumTopicId: 301322
|
||||
dashedName: override-inherited-methods
|
||||
@ -8,19 +8,19 @@ dashedName: override-inherited-methods
|
||||
|
||||
# --description--
|
||||
|
||||
In previous lessons, you learned that an object can inherit its behavior (methods) from another object by referencing its `prototype` object:
|
||||
Nas lições passadas, você aprendeu que um objeto pode herdar seus comportamentos (métodos) de outro objeto ao referenciar o `prototype` do objeto:
|
||||
|
||||
```js
|
||||
ChildObject.prototype = Object.create(ParentObject.prototype);
|
||||
```
|
||||
|
||||
Then the `ChildObject` received its own methods by chaining them onto its `prototype`:
|
||||
Em seguida, o `ChildObject` recebeu seu próprio método ao encadear eles neste `prototype`:
|
||||
|
||||
```js
|
||||
ChildObject.prototype.methodName = function() {...};
|
||||
```
|
||||
|
||||
It's possible to override an inherited method. It's done the same way - by adding a method to `ChildObject.prototype` using the same method name as the one to override. Here's an example of `Bird` overriding the `eat()` method inherited from `Animal`:
|
||||
É possível sobrescrever um método herdado. É feito da mesma maneira - ao adicionar o método a `ChildObject.prototype` utilizando o mesmo nome do método que aquele a ser sobrescrito. Aqui está um exemplo de `Bird` sobrescrevendo o método `eat()` herdado de `Animal`:
|
||||
|
||||
```js
|
||||
function Animal() { }
|
||||
@ -36,26 +36,26 @@ Bird.prototype.eat = function() {
|
||||
};
|
||||
```
|
||||
|
||||
If you have an instance `let duck = new Bird();` and you call `duck.eat()`, this is how JavaScript looks for the method on the `prototype` chain of `duck`:
|
||||
Se você tem uma instância `let duck = new Bird();` e você chamar `duck.eat()`, é assim que o JavaScript procura pelo método na cadeia de `prototype` de `duck`:
|
||||
|
||||
1. `duck` => Is `eat()` defined here? No.
|
||||
2. `Bird` => Is `eat()` defined here? => Yes. Execute it and stop searching.
|
||||
3. `Animal` => `eat()` is also defined, but JavaScript stopped searching before reaching this level.
|
||||
4. Object => JavaScript stopped searching before reaching this level.
|
||||
1. `duck` => o método `eat()` está definido aqui? Não.
|
||||
2. `Bird` => o método `eat()` está definido aqui? => Sim. Execute isso e pare de procurar.
|
||||
3. `Animal` => `eat()` também é definido, mas o JavaScript parou de procurar antes de chegar a este level.
|
||||
4. Objeto => JavaScript parou de procurar antes de chegar a este nível.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Override the `fly()` method for `Penguin` so that it returns the string `Alas, this is a flightless bird.`
|
||||
Sobrescreva o método `fly()` para `Penguin` para que retorne a string `Alas, this is a flightless bird.(Alas, isto é um pássaro que não voa.)`
|
||||
|
||||
# --hints--
|
||||
|
||||
`penguin.fly()` should return the string `Alas, this is a flightless bird.`
|
||||
`penguin.fly()` deve retornar a string `Alas, this is a flightless bird.(Infelizmente, este é um pássaro que não voa.)`
|
||||
|
||||
```js
|
||||
assert(penguin.fly() === 'Alas, this is a flightless bird.');
|
||||
```
|
||||
|
||||
The `bird.fly()` method should return the string `I am flying!`
|
||||
O método `bird.fly()` deve retornar a string `I am flying! (Eu estou voando)`
|
||||
|
||||
```js
|
||||
assert(new Bird().fly() === 'I am flying!');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7daf367417b2b2512b80
|
||||
title: Remember to Set the Constructor Property when Changing the Prototype
|
||||
title: Lembre-se de Definir a Propriedade Construtora quando Alterar o Protótipo
|
||||
challengeType: 1
|
||||
forumTopicId: 301323
|
||||
dashedName: remember-to-set-the-constructor-property-when-changing-the-prototype
|
||||
@ -8,7 +8,7 @@ dashedName: remember-to-set-the-constructor-property-when-changing-the-prototype
|
||||
|
||||
# --description--
|
||||
|
||||
There is one crucial side effect of manually setting the prototype to a new object. It erases the `constructor` property! This property can be used to check which constructor function created the instance, but since the property has been overwritten, it now gives false results:
|
||||
Tem um efeito colateral crucial de definir manualmente o protótipo de um novo objeto. Isso apaga a propriedade `construtor`! Essa propriedade pode ser utilizada para verificar qual função construtora criou a instância, mas já que a propriedade foi sobrescrita, agora retorna resultados falsos:
|
||||
|
||||
```js
|
||||
duck.constructor === Bird;
|
||||
@ -16,9 +16,9 @@ duck.constructor === Object;
|
||||
duck instanceof Bird;
|
||||
```
|
||||
|
||||
In order, these expressions would evaluate to `false`, `true`, and `true`.
|
||||
Em ordem, essas expressões seriam avaliadas a `false`, `true` e `true`.
|
||||
|
||||
To fix this, whenever a prototype is manually set to a new object, remember to define the `constructor` property:
|
||||
Para corrigir isso, toda vez que o protótipo é manualmente definido para um novo objeto, lembre-se de definir a propriedade `construtor`:
|
||||
|
||||
```js
|
||||
Bird.prototype = {
|
||||
@ -35,11 +35,11 @@ Bird.prototype = {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Define the `constructor` property on the `Dog` `prototype`.
|
||||
Define a propriedade `construtor` no `prototype` de `Dog`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Dog.prototype` should set the `constructor` property.
|
||||
`Dog.prototype` deve definir a propriedade `construtor`.
|
||||
|
||||
```js
|
||||
assert(Dog.prototype.constructor === Dog);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db1367417b2b2512b86
|
||||
title: Reset an Inherited Constructor Property
|
||||
title: Redefina uma Propriedade Construtora Herdada
|
||||
challengeType: 1
|
||||
forumTopicId: 301324
|
||||
dashedName: reset-an-inherited-constructor-property
|
||||
@ -8,9 +8,9 @@ dashedName: reset-an-inherited-constructor-property
|
||||
|
||||
# --description--
|
||||
|
||||
When an object inherits its `prototype` from another object, it also inherits the supertype's constructor property.
|
||||
Quando um objeto herda seu `protótipo` de outro objeto, ele também herda a propriedade construtora do supertipo.
|
||||
|
||||
Here's an example:
|
||||
Aqui está um exemplo:
|
||||
|
||||
```js
|
||||
function Bird() { }
|
||||
@ -19,7 +19,7 @@ let duck = new Bird();
|
||||
duck.constructor
|
||||
```
|
||||
|
||||
But `duck` and all instances of `Bird` should show that they were constructed by `Bird` and not `Animal`. To do so, you can manually set the constructor property of `Bird` to the `Bird` object:
|
||||
Mas `duck` e todas as instâncias de `Bird` devem mostrar que eles foram construídos por `Bird` e não `Animal`. Para fazer isso, você pode manualmente definir a propriedade construtora de `Bird` para o objeto `Bird`:
|
||||
|
||||
```js
|
||||
Bird.prototype.constructor = Bird;
|
||||
@ -28,29 +28,29 @@ duck.constructor
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the code so `duck.constructor` and `beagle.constructor` return their respective constructors.
|
||||
Corrija o código para que `duck.constructor` e `beagle.constructor` retornem seus respectivos construtores.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Bird.prototype` should be an instance of `Animal`.
|
||||
`Bird.prototype` deve ser uma instância de `Animal`.
|
||||
|
||||
```js
|
||||
assert(Animal.prototype.isPrototypeOf(Bird.prototype));
|
||||
```
|
||||
|
||||
`duck.constructor` should return `Bird`.
|
||||
`duck.constructor` deve retornar `Bird`.
|
||||
|
||||
```js
|
||||
assert(duck.constructor === Bird);
|
||||
```
|
||||
|
||||
`Dog.prototype` should be an instance of `Animal`.
|
||||
`Dog.prototype` deve ser uma instância de `Animal`.
|
||||
|
||||
```js
|
||||
assert(Animal.prototype.isPrototypeOf(Dog.prototype));
|
||||
```
|
||||
|
||||
`beagle.constructor` should return `Dog`.
|
||||
`beagle.constructor` deve retornar `Dog`.
|
||||
|
||||
```js
|
||||
assert(beagle.constructor === Dog);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db1367417b2b2512b85
|
||||
title: Set the Child's Prototype to an Instance of the Parent
|
||||
title: Defina o Protótipo de Child para ser uma Instância do Parent
|
||||
challengeType: 1
|
||||
forumTopicId: 301325
|
||||
dashedName: set-the-childs-prototype-to-an-instance-of-the-parent
|
||||
@ -8,30 +8,30 @@ dashedName: set-the-childs-prototype-to-an-instance-of-the-parent
|
||||
|
||||
# --description--
|
||||
|
||||
In the previous challenge you saw the first step for inheriting behavior from the supertype (or parent) `Animal`: making a new instance of `Animal`.
|
||||
No desafio anterior, você viu o primeiro passo para herdar comportamento do supertipo (ou parente) `Animal`: fazendo uma instância de `Animal`.
|
||||
|
||||
This challenge covers the next step: set the `prototype` of the subtype (or child)—in this case, `Bird`—to be an instance of `Animal`.
|
||||
Este desafio cobre o próximo passo: definir o `prototype` do subtipo (ou filho) - neste caso, `Bird` - para ser uma instância de `Animal`.
|
||||
|
||||
```js
|
||||
Bird.prototype = Object.create(Animal.prototype);
|
||||
```
|
||||
|
||||
Remember that the `prototype` is like the "recipe" for creating an object. In a way, the recipe for `Bird` now includes all the key "ingredients" from `Animal`.
|
||||
Lembre-se que o `prototype` é como uma receita para criar um objeto. De certa forma, a receita para `Bird` agora inclui todos os "ingredientes" chave para `Animal`.
|
||||
|
||||
```js
|
||||
let duck = new Bird("Donald");
|
||||
duck.eat();
|
||||
```
|
||||
|
||||
`duck` inherits all of `Animal`'s properties, including the `eat` method.
|
||||
`duck` herda todas as propriedades de `Animal`, incluindo o método `eat`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the code so that instances of `Dog` inherit from `Animal`.
|
||||
Modifique o código para que as instâncias de `Dog` herdem de `Animal`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Dog.prototype` should be an instance of `Animal`.
|
||||
`Dog.prototype` deve ser uma instância de `Animal`.
|
||||
|
||||
```js
|
||||
assert(Animal.prototype.isPrototypeOf(Dog.prototype));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dae367417b2b2512b7b
|
||||
title: Understand Own Properties
|
||||
title: Entendendo Propriedades Próprias
|
||||
challengeType: 1
|
||||
forumTopicId: 301326
|
||||
dashedName: understand-own-properties
|
||||
@ -8,7 +8,7 @@ dashedName: understand-own-properties
|
||||
|
||||
# --description--
|
||||
|
||||
In the following example, the `Bird` constructor defines two properties: `name` and `numLegs`:
|
||||
No próximo exemplo, o construtor de `Bird` define duas propriedades: `name` e `numLegs`:
|
||||
|
||||
```js
|
||||
function Bird(name) {
|
||||
@ -20,7 +20,7 @@ let duck = new Bird("Donald");
|
||||
let canary = new Bird("Tweety");
|
||||
```
|
||||
|
||||
`name` and `numLegs` are called <dfn>own properties</dfn>, because they are defined directly on the instance object. That means that `duck` and `canary` each has its own separate copy of these properties. In fact every instance of `Bird` will have its own copy of these properties. The following code adds all of the own properties of `duck` to the array `ownProps`:
|
||||
`name` e `numLegs` são chamados <dfn>own properties</dfn>, pois são definidos diretamente na instância do objeto. Isso significa que cada `duck` e `canary` possuem suas próprias cópias separadas destas propriedades. Na verdade, toda instância de `Bird` terá sua própria cópia dessas propriedades. O código a seguir adiciona todas as propriedades próprias (own properties) de `duck` para o array `ownProps`:
|
||||
|
||||
```js
|
||||
let ownProps = [];
|
||||
@ -34,27 +34,27 @@ for (let property in duck) {
|
||||
console.log(ownProps);
|
||||
```
|
||||
|
||||
The console would display the value `["name", "numLegs"]`.
|
||||
O console irá exibir o valor `["name", "numLegs"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the own properties of `canary` to the array `ownProps`.
|
||||
Adicione as propriedades próprias do `canary` para o array `ownProps`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`ownProps` should include the values `numLegs` and `name`.
|
||||
`ownProps` deve incluir os valores `numLegs` e `name`.
|
||||
|
||||
```js
|
||||
assert(ownProps.indexOf('name') !== -1 && ownProps.indexOf('numLegs') !== -1);
|
||||
```
|
||||
|
||||
You should solve this challenge without using the built in method `Object.keys()`.
|
||||
Você deve resolver este desafio sem utilizar o método nativo `Object.keys()`.
|
||||
|
||||
```js
|
||||
assert(!/Object(\.keys|\[(['"`])keys\2\])/.test(code));
|
||||
```
|
||||
|
||||
You should solve this challenge without hardcoding the `ownProps` array.
|
||||
Você deve resolver este desafio sem definir o array `ownProps` de forma fixa no código.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7daf367417b2b2512b7e
|
||||
title: Understand the Constructor Property
|
||||
title: Entendendo a Propriedade Construtora
|
||||
challengeType: 1
|
||||
forumTopicId: 301327
|
||||
dashedName: understand-the-constructor-property
|
||||
@ -8,7 +8,7 @@ dashedName: understand-the-constructor-property
|
||||
|
||||
# --description--
|
||||
|
||||
There is a special `constructor` property located on the object instances `duck` and `beagle` that were created in the previous challenges:
|
||||
Tem uma propriedade especial do `construtor` localizada nas instâncias dos objetos `duck` e `beagle` que foram criados nos desafios anteriores:
|
||||
|
||||
```js
|
||||
let duck = new Bird();
|
||||
@ -18,9 +18,9 @@ console.log(duck.constructor === Bird);
|
||||
console.log(beagle.constructor === Dog);
|
||||
```
|
||||
|
||||
Both of these `console.log` calls would display `true` in the console.
|
||||
Ambas as chamadas a `console.log` irão exibir `true` no console.
|
||||
|
||||
Note that the `constructor` property is a reference to the constructor function that created the instance. The advantage of the `constructor` property is that it's possible to check for this property to find out what kind of object it is. Here's an example of how this could be used:
|
||||
Note que a propriedade `construtor` é uma referência a função construtora que criou a instância. A vantagem da propriedade `construtor` é que se torna possível verificar essa propriedade para descobrir qual o tipo do objeto. Aqui está um exemplo de como isso poderia ser utilizado:
|
||||
|
||||
```js
|
||||
function joinBirdFraternity(candidate) {
|
||||
@ -32,27 +32,27 @@ function joinBirdFraternity(candidate) {
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Since the `constructor` property can be overwritten (which will be covered in the next two challenges) it’s generally better to use the `instanceof` method to check the type of an object.
|
||||
**Note:** Desde que a propriedade `construtor` pode ser sobrescrita (o que será abordado nos próximos dois desafios), geralmente é melhor utilizar o método `instanceof` para verificar o tipo de um objeto.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a `joinDogFraternity` function that takes a `candidate` parameter and, using the `constructor` property, return `true` if the candidate is a `Dog`, otherwise return `false`.
|
||||
Escreva a função `joinDogFraternity` que recebe o parâmetro `candidate` e, utilizando a propriedade `construtora`, retorne `true` se o candidato é um `Dog`, e caso não seja, retorne `false`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`joinDogFraternity` should be defined as a function.
|
||||
`joinDogFraternity` deve ser definido como uma função.
|
||||
|
||||
```js
|
||||
assert(typeof joinDogFraternity === 'function');
|
||||
```
|
||||
|
||||
`joinDogFraternity` should return `true` if `candidate` is an instance of `Dog`.
|
||||
`joinDogFraternity` deve retornar `true` se `candidate` for uma instância de `Dog`.
|
||||
|
||||
```js
|
||||
assert(joinDogFraternity(new Dog('')) === true);
|
||||
```
|
||||
|
||||
`joinDogFraternity` should use the `constructor` property.
|
||||
`joinDogFraternity` deve utilizar a propriedade `construtor`.
|
||||
|
||||
```js
|
||||
assert(/\.constructor/.test(code) && !/instanceof/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db2367417b2b2512b8b
|
||||
title: Understand the Immediately Invoked Function Expression (IIFE)
|
||||
title: Entenda a Expressão de Função Invocada Imediatamente (IIFE)
|
||||
challengeType: 1
|
||||
forumTopicId: 301328
|
||||
dashedName: understand-the-immediately-invoked-function-expression-iife
|
||||
@ -8,7 +8,7 @@ dashedName: understand-the-immediately-invoked-function-expression-iife
|
||||
|
||||
# --description--
|
||||
|
||||
A common pattern in JavaScript is to execute a function as soon as it is declared:
|
||||
Um padrão comum em JavaScript é executar a função assim que ela é declarada:
|
||||
|
||||
```js
|
||||
(function () {
|
||||
@ -16,23 +16,23 @@ A common pattern in JavaScript is to execute a function as soon as it is declare
|
||||
})();
|
||||
```
|
||||
|
||||
This is an anonymous function expression that executes right away, and outputs `Chirp, chirp!` immediately.
|
||||
Essa é uma expressão de função anônima que executa logo após ser declarada, e exibe imediatamente no console `Chirp, chirp!`.
|
||||
|
||||
Note that the function has no name and is not stored in a variable. The two parentheses () at the end of the function expression cause it to be immediately executed or invoked. This pattern is known as an <dfn>immediately invoked function expression</dfn> or <dfn>IIFE</dfn>.
|
||||
Note que a função não possui nome e não é armazenada em uma variável. Os dois parênteses () ao final da expressão da função faz com que ela seja imediatamente executada ou invocada. Este padrão é conhecido como <dfn>immediately invoked function expression (expressão de função invocada imediatamente)</dfn> ou <dfn>IIFE</dfn>.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Rewrite the function `makeNest` and remove its call so instead it's an anonymous immediately invoked function expression (IIFE).
|
||||
Rescreva a função `makeNest` e remova a chamada a ela para que no lugar seja uma expressão de função anônima imediatamente invocada (IIFE).
|
||||
|
||||
# --hints--
|
||||
|
||||
The function should be anonymous.
|
||||
A função deve ser anônima.
|
||||
|
||||
```js
|
||||
assert(/\((function|\(\))(=>|\(\)){?/.test(code.replace(/\s/g, '')));
|
||||
```
|
||||
|
||||
Your function should have parentheses at the end of the expression to call it immediately.
|
||||
Sua função deve ter parênteses no final da expressão para chamar ela imediatamente.
|
||||
|
||||
```js
|
||||
assert(/\(.*(\)\(|\}\(\))\)/.test(code.replace(/[\s;]/g, '')));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db0367417b2b2512b82
|
||||
title: Understand the Prototype Chain
|
||||
title: Entenda o Protótipo Cadeia
|
||||
challengeType: 1
|
||||
forumTopicId: 301329
|
||||
dashedName: understand-the-prototype-chain
|
||||
@ -8,7 +8,7 @@ dashedName: understand-the-prototype-chain
|
||||
|
||||
# --description--
|
||||
|
||||
All objects in JavaScript (with a few exceptions) have a `prototype`. Also, an object’s `prototype` itself is an object.
|
||||
Todos os objetos em JavaScript (com algumas exceções) possuem um `prototype`. Além de que, um `prototype` de um objeto ser um próprio objeto.
|
||||
|
||||
```js
|
||||
function Bird(name) {
|
||||
@ -18,28 +18,28 @@ function Bird(name) {
|
||||
typeof Bird.prototype;
|
||||
```
|
||||
|
||||
Because a `prototype` is an object, a `prototype` can have its own `prototype`! In this case, the `prototype` of `Bird.prototype` is `Object.prototype`:
|
||||
Devido ao fato de um `prototype` ser um objeto, um `prototype` pode ter seu próprio `prototype`! Neste caso, o `prototype` de `Bird.prototype` é um `Object.prototype`:
|
||||
|
||||
```js
|
||||
Object.prototype.isPrototypeOf(Bird.prototype);
|
||||
```
|
||||
|
||||
How is this useful? You may recall the `hasOwnProperty` method from a previous challenge:
|
||||
Como isso é útil? Você pode ser lembrar que o método `hasOwnProperty` do desafio anterior:
|
||||
|
||||
```js
|
||||
let duck = new Bird("Donald");
|
||||
duck.hasOwnProperty("name");
|
||||
```
|
||||
|
||||
The `hasOwnProperty` method is defined in `Object.prototype`, which can be accessed by `Bird.prototype`, which can then be accessed by `duck`. This is an example of the `prototype` chain. In this `prototype` chain, `Bird` is the `supertype` for `duck`, while `duck` is the `subtype`. `Object` is a `supertype` for both `Bird` and `duck`. `Object` is a `supertype` for all objects in JavaScript. Therefore, any object can use the `hasOwnProperty` method.
|
||||
O método `hasOwnProperty` é definido em `Object.prototype`, o qual pode ser acessado por `Bird.prototype`, o qual pode ser acessado por `duck`. Este é um exemplo de cadeia de `prototype`. Nesta cadeia de `prototype`, `Bird` é um `supertipo` para `duck`, enquanto `duck` é o `subtipo`. `Object` é um `supertipo` para ambos `Bird` e `duck`. `Object` é um `supertipo` para todos os objetos em JavaScript. Desta forma, qualquer objeto pode utilizar o método `hasOwnProperty`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the code to show the correct prototype chain.
|
||||
Modifique o código para mostrar corretamente a cadeia de protótipo.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should show that `Object.prototype` is the prototype of `Dog.prototype`
|
||||
Seu código deve mostrar que `Object.prototype` é o protótipo de `Dog.prototype`
|
||||
|
||||
```js
|
||||
assert(/Object\.prototype\.isPrototypeOf/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db0367417b2b2512b81
|
||||
title: Understand Where an Object’s Prototype Comes From
|
||||
title: Entenda de Onde Vem o Protótipo de um Objeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301330
|
||||
dashedName: understand-where-an-objects-prototype-comes-from
|
||||
@ -8,7 +8,7 @@ dashedName: understand-where-an-objects-prototype-comes-from
|
||||
|
||||
# --description--
|
||||
|
||||
Just like people inherit genes from their parents, an object inherits its `prototype` directly from the constructor function that created it. For example, here the `Bird` constructor creates the `duck` object:
|
||||
Assim como uma pessoa herda o gene de seus parentes, um objeto herda seu `prototype` diretamente da função construtora que o criou. Por exemplo, aqui o construtor de `Bird` cria um objeto `duck`:
|
||||
|
||||
```js
|
||||
function Bird(name) {
|
||||
@ -18,21 +18,21 @@ function Bird(name) {
|
||||
let duck = new Bird("Donald");
|
||||
```
|
||||
|
||||
`duck` inherits its `prototype` from the `Bird` constructor function. You can show this relationship with the `isPrototypeOf` method:
|
||||
`duck` herda seu `prototype` da função construtora de `Bird`. Você pode mostrar a relação com o método `isPrototypeOf`:
|
||||
|
||||
```js
|
||||
Bird.prototype.isPrototypeOf(duck);
|
||||
```
|
||||
|
||||
This would return `true`.
|
||||
Isso iria retornar `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use `isPrototypeOf` to check the `prototype` of `beagle`.
|
||||
Utilize `isPrototypeOf` para verificar o `prototype` de `beagle`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should show that `Dog.prototype` is the `prototype` of `beagle`
|
||||
Você deve mostrar que o `Dog.prototype` é um `protótipo` de `beagle`
|
||||
|
||||
```js
|
||||
assert(/Dog\.prototype\.isPrototypeOf\(beagle\)/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dad367417b2b2512b78
|
||||
title: Use a Constructor to Create Objects
|
||||
title: Utilize um Construtor para Criar Objetos
|
||||
challengeType: 1
|
||||
forumTopicId: 18233
|
||||
dashedName: use-a-constructor-to-create-objects
|
||||
@ -8,7 +8,7 @@ dashedName: use-a-constructor-to-create-objects
|
||||
|
||||
# --description--
|
||||
|
||||
Here's the `Bird` constructor from the previous challenge:
|
||||
Aqui está o construtor de `Bird` do desafio anterior:
|
||||
|
||||
```js
|
||||
function Bird() {
|
||||
@ -20,9 +20,9 @@ function Bird() {
|
||||
let blueBird = new Bird();
|
||||
```
|
||||
|
||||
**NOTE:** `this` inside the constructor always refers to the object being created.
|
||||
**Note:** `this` dentro do construtor sempre refere-se ao objeto sendo criado.
|
||||
|
||||
Notice that the `new` operator is used when calling a constructor. This tells JavaScript to create a new instance of `Bird` called `blueBird`. Without the `new` operator, `this` inside the constructor would not point to the newly created object, giving unexpected results. Now `blueBird` has all the properties defined inside the `Bird` constructor:
|
||||
Note que o operador `new` é usado quando chamamos o construtor. Isso avisa ao JavaScript para criar uma nova instância de `Bird` chamado `blueBird`. Sem o operador `new`, `this` dentro do construtor não iria apontar para o objeto recentemente criado, dando resultados inesperados. Agora `blueBird` possui todas as propriedades definidas dentro do construtor `Bird`:
|
||||
|
||||
```js
|
||||
blueBird.name;
|
||||
@ -30,7 +30,7 @@ blueBird.color;
|
||||
blueBird.numLegs;
|
||||
```
|
||||
|
||||
Just like any other object, its properties can be accessed and modified:
|
||||
Assim como qualquer outro objeto, suas propriedades podem ser acessadas e modificadas:
|
||||
|
||||
```js
|
||||
blueBird.name = 'Elvira';
|
||||
@ -39,17 +39,17 @@ blueBird.name;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `Dog` constructor from the last lesson to create a new instance of `Dog`, assigning it to a variable `hound`.
|
||||
Utilize o construtor de `Dog` da última lição para criar uma nova instância de `Dog`, atribuindo a instância para a variável `hound`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hound` should be created using the `Dog` constructor.
|
||||
`hound` deve ser criado utilizando o construtor `Dog`.
|
||||
|
||||
```js
|
||||
assert(hound instanceof Dog);
|
||||
```
|
||||
|
||||
Your code should use the `new` operator to create an instance of `Dog`.
|
||||
Seu código deve utilizar o operador `new` para criar uma instância de `Dog`.
|
||||
|
||||
```js
|
||||
assert(code.match(/new/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db2367417b2b2512b89
|
||||
title: Use a Mixin to Add Common Behavior Between Unrelated Objects
|
||||
title: Utilize Mixin para Adicionar Comportamentos Comuns Entre Objetos Não-Relacionados
|
||||
challengeType: 1
|
||||
forumTopicId: 301331
|
||||
dashedName: use-a-mixin-to-add-common-behavior-between-unrelated-objects
|
||||
@ -8,9 +8,9 @@ dashedName: use-a-mixin-to-add-common-behavior-between-unrelated-objects
|
||||
|
||||
# --description--
|
||||
|
||||
As you have seen, behavior is shared through inheritance. However, there are cases when inheritance is not the best solution. Inheritance does not work well for unrelated objects like `Bird` and `Airplane`. They can both fly, but a `Bird` is not a type of `Airplane` and vice versa.
|
||||
Como você já viu, comportamento é compartilhado através de herança. Porém, existem casos em que a herança não é a melhor solução. Herança não funciona muito bem para objetos não-relacionados como `Bird` e `Airplane`. Ambos podem voar, mas um `Bird` não é um tipo de `Airplane` e vice versa.
|
||||
|
||||
For unrelated objects, it's better to use <dfn>mixins</dfn>. A mixin allows other objects to use a collection of functions.
|
||||
Para objetos não-relacionados, é melhor usar <dfn>mixins</dfn>. Um mixin permite outros objetos para utilizar uma coleção de funções.
|
||||
|
||||
```js
|
||||
let flyMixin = function(obj) {
|
||||
@ -20,7 +20,7 @@ let flyMixin = function(obj) {
|
||||
};
|
||||
```
|
||||
|
||||
The `flyMixin` takes any object and gives it the `fly` method.
|
||||
O `flyMixin` recebe qualquer objeto e da a ele o método `fly`.
|
||||
|
||||
```js
|
||||
let bird = {
|
||||
@ -37,36 +37,36 @@ flyMixin(bird);
|
||||
flyMixin(plane);
|
||||
```
|
||||
|
||||
Here `bird` and `plane` are passed into `flyMixin`, which then assigns the `fly` function to each object. Now `bird` and `plane` can both fly:
|
||||
Aqui `bird` e `plane` são passados para `flyMixin`, o que em seguida atribui a função `fly` para cada objeto. Agora `bird` e `plane` podem ambos voar:
|
||||
|
||||
```js
|
||||
bird.fly();
|
||||
plane.fly();
|
||||
```
|
||||
|
||||
The console would display the string `Flying, wooosh!` twice, once for each `.fly()` call.
|
||||
O console irá mostrar a string `Flying, woosh!` duas vezes, uma para cada chamada a `.fly()`.
|
||||
|
||||
Note how the mixin allows for the same `fly` method to be reused by unrelated objects `bird` and `plane`.
|
||||
Note como o mixin permite que o mesmo método `fly` seja reutilizado por objetos não-relacionados `bird` e `plane`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a mixin named `glideMixin` that defines a method named `glide`. Then use the `glideMixin` to give both `bird` and `boat` the ability to glide.
|
||||
Crie um mixin chamado `glideMixin` que define o método chamado `glide`. Em seguida, use `glideMixin` para dar ambos `bird` e `boat` a habilidade de deslizar (glide).
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should declare a `glideMixin` variable that is a function.
|
||||
Seu código deve declarar a variável `glideMixin`, a qual é uma função.
|
||||
|
||||
```js
|
||||
assert(typeof glideMixin === 'function');
|
||||
```
|
||||
|
||||
Your code should use the `glideMixin` on the `bird` object to give it the `glide` method.
|
||||
Seu código deve utilizar o `glideMixin` no objeto `bird` para dar ao objeto o método `glide`.
|
||||
|
||||
```js
|
||||
assert(typeof bird.glide === 'function');
|
||||
```
|
||||
|
||||
Your code should use the `glideMixin` on the `boat` object to give it the `glide` method.
|
||||
Seu código deve utilizar `glideMixin` no objeto `boat` para dar ao objeto o método `glide`.
|
||||
|
||||
```js
|
||||
assert(typeof boat.glide === 'function');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db2367417b2b2512b8c
|
||||
title: Use an IIFE to Create a Module
|
||||
title: Utilize um IIFE para Criar um Módulo
|
||||
challengeType: 1
|
||||
forumTopicId: 301332
|
||||
dashedName: use-an-iife-to-create-a-module
|
||||
@ -8,7 +8,7 @@ dashedName: use-an-iife-to-create-a-module
|
||||
|
||||
# --description--
|
||||
|
||||
An immediately invoked function expression (IIFE) is often used to group related functionality into a single object or <dfn>module</dfn>. For example, an earlier challenge defined two mixins:
|
||||
Uma expressão de função imediatamente invocada (IIFE) é frequentemente utilizado para agrupar funcionalidades relacionadas para um único objeto ou <dfn>module</dfn>. Por exemplo, um desafio anterior definiu dois mixins:
|
||||
|
||||
```js
|
||||
function glideMixin(obj) {
|
||||
@ -23,7 +23,7 @@ function flyMixin(obj) {
|
||||
}
|
||||
```
|
||||
|
||||
We can group these mixins into a module as follows:
|
||||
Nos podemos agrupar esses mixins em um módulo como o seguinte:
|
||||
|
||||
```js
|
||||
let motionModule = (function () {
|
||||
@ -42,7 +42,7 @@ let motionModule = (function () {
|
||||
})();
|
||||
```
|
||||
|
||||
Note that you have an immediately invoked function expression (IIFE) that returns an object `motionModule`. This returned object contains all of the mixin behaviors as properties of the object. The advantage of the module pattern is that all of the motion behaviors can be packaged into a single object that can then be used by other parts of your code. Here is an example using it:
|
||||
Note que você possui uma expressão de função imediatamente invocada (IIFE) que retorna um objeto `motionModule`. Esse objeto retornado contém todos os comportamentos de mixin como propriedades do objeto. A vantagem do padrão módulo é que todos os comportamentos de movimento podem ser embalados em um único objeto que pode em seguida ser usado por outras partes do seu código. Aqui está um exemplo utilizando isso:
|
||||
|
||||
```js
|
||||
motionModule.glideMixin(duck);
|
||||
@ -51,23 +51,23 @@ duck.glide();
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a module named `funModule` to wrap the two mixins `isCuteMixin` and `singMixin`. `funModule` should return an object.
|
||||
Crie um módulo chamado `funModule` para embrulhar os dois mixins `isCuteMixin` e `singMixin`. `funModule` deve retornar um objeto.
|
||||
|
||||
# --hints--
|
||||
|
||||
`funModule` should be defined and return an object.
|
||||
`funModule` deve ser definido e retornar um objeto.
|
||||
|
||||
```js
|
||||
assert(typeof funModule === 'object');
|
||||
```
|
||||
|
||||
`funModule.isCuteMixin` should access a function.
|
||||
`funModule.isCuteMixin` deve acessar uma função.
|
||||
|
||||
```js
|
||||
assert(typeof funModule.isCuteMixin === 'function');
|
||||
```
|
||||
|
||||
`funModule.singMixin` should access a function.
|
||||
`funModule.singMixin` deve acessar uma função.
|
||||
|
||||
```js
|
||||
assert(typeof funModule.singMixin === 'function');
|
||||
|
@ -1,7 +1,7 @@
|
||||
---
|
||||
id: 587d7db2367417b2b2512b8a
|
||||
title: >-
|
||||
Use Closure to Protect Properties Within an Object from Being Modified Externally
|
||||
Use Fecho para Proteger Propriedades Dentro de um Objeto de Serem Modificados Externamente
|
||||
challengeType: 1
|
||||
forumTopicId: 18234
|
||||
dashedName: >-
|
||||
@ -10,15 +10,15 @@ dashedName: >-
|
||||
|
||||
# --description--
|
||||
|
||||
In the previous challenge, `bird` had a public property `name`. It is considered public because it can be accessed and changed outside of `bird`'s definition.
|
||||
No desafio anterior, `bird` possuía uma propriedade pública `name`. É considerado publico porque ele pode ser acessado e modificado fora da definição de `bird`.
|
||||
|
||||
```js
|
||||
bird.name = "Duffy";
|
||||
```
|
||||
|
||||
Therefore, any part of your code can easily change the name of `bird` to any value. Think about things like passwords and bank accounts being easily changeable by any part of your codebase. That could cause a lot of issues.
|
||||
Portanto, qualquer parte do seu código pode facilmente alterar o nome do `bird` para qualquer valor. Pense sobre coisas como senhas e contas de banco sendo facilmente modificáveis em qualquer parte do seu código. Isso poderia causar inúmeros problemas.
|
||||
|
||||
The simplest way to make this public property private is by creating a variable within the constructor function. This changes the scope of that variable to be within the constructor function versus available globally. This way, the variable can only be accessed and changed by methods also within the constructor function.
|
||||
A forma mais simples para tornar essa propriedade pública em privada, seria criando uma variável dentro da função constructor. Isso alteraria o escopo daquela variável para ser apenas o escopo da função construtora ao invés de globalmente disponível. Dessa maneira, a variável pode ser acessada e modificada apenas pelos métodos dentro da função construtora.
|
||||
|
||||
```js
|
||||
function Bird() {
|
||||
@ -32,27 +32,27 @@ let ducky = new Bird();
|
||||
ducky.getHatchedEggCount();
|
||||
```
|
||||
|
||||
Here `getHatchedEggCount` is a privileged method, because it has access to the private variable `hatchedEgg`. This is possible because `hatchedEgg` is declared in the same context as `getHatchedEggCount`. In JavaScript, a function always has access to the context in which it was created. This is called `closure`.
|
||||
Aqui `getHatchedEggCount` é um método privilegiado, porque ele possui acesso à variável privada `hatchedEgg`. Isso é possível porque `hatchedEgg` é declarado no mesmo contexto que `getHatchedEggCount`. Em JavaScript, a função sempre possui acesso ao contexto na qual foi criada. Isso é chamado de `closure(fecho)`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change how `weight` is declared in the `Bird` function so it is a private variable. Then, create a method `getWeight` that returns the value of `weight` 15.
|
||||
Modifique como `weight` é declarado na função `Bird` para que seja uma variável privada. Em seguida, crie o método `getWeight` que retorna o valor de `weight` 15.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `weight` property should be a private variable and should be assigned the value of `15`.
|
||||
A propriedade `weight` deve ser uma variável privada e deve ser atribuída a ela o valor `15`.
|
||||
|
||||
```js
|
||||
assert(code.match(/(var|let|const)\s+weight\s*\=\s*15\;?/g));
|
||||
```
|
||||
|
||||
Your code should create a method in `Bird` called `getWeight` that returns the value of the private variable `weight`.
|
||||
Seu código deve criar o método dentro de `Bird` chamado `getWeight` que retorna o valor da variável privada `weight`.
|
||||
|
||||
```js
|
||||
assert(new Bird().getWeight() === 15);
|
||||
```
|
||||
|
||||
Your `getWeight` function should return the private variable `weight`.
|
||||
Sua função `getWeight` deve retornar a variável privada `weight`.
|
||||
|
||||
```js
|
||||
assert(code.match(/((return\s+)|(\(\s*\)\s*\=\>\s*))weight\;?/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dac367417b2b2512b74
|
||||
title: Use Dot Notation to Access the Properties of an Object
|
||||
title: Use Ponto Notação para Acessar as Propriedades de um Objeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301333
|
||||
dashedName: use-dot-notation-to-access-the-properties-of-an-object
|
||||
@ -8,7 +8,7 @@ dashedName: use-dot-notation-to-access-the-properties-of-an-object
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge created an object with various properties. Now you'll see how to access the values of those properties. Here's an example:
|
||||
O último desafio criou um objeto com várias propriedades. Agora você verá como acessar os valores dessas propriedades. Aqui está um exemplo:
|
||||
|
||||
```js
|
||||
let duck = {
|
||||
@ -18,21 +18,21 @@ let duck = {
|
||||
console.log(duck.name);
|
||||
```
|
||||
|
||||
Dot notation is used on the object name, `duck`, followed by the name of the property, `name`, to access the value of `Aflac`.
|
||||
Ponto notação é utilizado no nome do objeto, `duck`, seguido pelo nome da propriedade, `name`, para acessar o valor de `Aflac`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Print both properties of the `dog` object to your console.
|
||||
Exiba ambas as propriedades do objeto `dog` no seu console.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use `console.log` to print the value for the `name` property of the `dog` object.
|
||||
Seu código deve usar `console.log` para exibir o valor da propriedade `name` do objeto `dog`.
|
||||
|
||||
```js
|
||||
assert(/console.log\(.*dog\.name.*\)/g.test(code));
|
||||
```
|
||||
|
||||
Your code should use `console.log` to print the value for the `numLegs` property of the `dog` object.
|
||||
Seu código deve usar `console.log` para exibir o valor para a propriedade `numLegs` do objeto `dog`.
|
||||
|
||||
```js
|
||||
assert(/console.log\(.*dog\.numLegs.*\)/g.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db0367417b2b2512b83
|
||||
title: Use Inheritance So You Don't Repeat Yourself
|
||||
title: Utilize Herança Para Que Você Não Repita Código Você Mesmo
|
||||
challengeType: 1
|
||||
forumTopicId: 301334
|
||||
dashedName: use-inheritance-so-you-dont-repeat-yourself
|
||||
@ -8,9 +8,9 @@ dashedName: use-inheritance-so-you-dont-repeat-yourself
|
||||
|
||||
# --description--
|
||||
|
||||
There's a principle in programming called <dfn>Don't Repeat Yourself (DRY)</dfn>. The reason repeated code is a problem is because any change requires fixing code in multiple places. This usually means more work for programmers and more room for errors.
|
||||
Tem um princípio da programação chamado <dfn>Don't Repeat Yourself (DRY) (Não Repita Você Mesmo)</dfn>. O motivo pelo qual código repetido é um problema se deve ao fato de qualquer alteração exige correção de código em vários locais. Geralmente isso significa mais trabalho para os programadores e mais espaço para erros.
|
||||
|
||||
Notice in the example below that the `describe` method is shared by `Bird` and `Dog`:
|
||||
Note que o exemplo abaixo que `descreve` o método é compartilhado por `Bird` e `Dog`:
|
||||
|
||||
```js
|
||||
Bird.prototype = {
|
||||
@ -28,7 +28,7 @@ Dog.prototype = {
|
||||
};
|
||||
```
|
||||
|
||||
The `describe` method is repeated in two places. The code can be edited to follow the DRY principle by creating a `supertype` (or parent) called `Animal`:
|
||||
O método `describe` é repetido em dois locais. O código pode ser editado para seguir o princípio DRY (Não Repita Você Mesmo) ao criar um `supertipo` (ou parente) chamado `Animal`:
|
||||
|
||||
```js
|
||||
function Animal() { };
|
||||
@ -41,7 +41,7 @@ Animal.prototype = {
|
||||
};
|
||||
```
|
||||
|
||||
Since `Animal` includes the `describe` method, you can remove it from `Bird` and `Dog`:
|
||||
Desde que `Animal` inclui o método `describe`, você pode remover ele de `Bird` e `Dog`:
|
||||
|
||||
```js
|
||||
Bird.prototype = {
|
||||
@ -55,23 +55,23 @@ Dog.prototype = {
|
||||
|
||||
# --instructions--
|
||||
|
||||
The `eat` method is repeated in both `Cat` and `Bear`. Edit the code in the spirit of DRY by moving the `eat` method to the `Animal` `supertype`.
|
||||
O método `eat` é repetido em `Cat` e `Bear`. Edite o código no espírito do princípio DRY ao mover o método `eat` do `supertipo` de `Animal`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Animal.prototype` should have the `eat` property.
|
||||
`Animal.prototype` deve ter a propriedade `eat`.
|
||||
|
||||
```js
|
||||
assert(Animal.prototype.hasOwnProperty('eat'));
|
||||
```
|
||||
|
||||
`Bear.prototype` should not have the `eat` property.
|
||||
`Bear.prototype` não deve ter a propriedade `eat`.
|
||||
|
||||
```js
|
||||
assert(!Bear.prototype.hasOwnProperty('eat'));
|
||||
```
|
||||
|
||||
`Cat.prototype` should not have the `eat` property.
|
||||
`Cat.propotype` não deve ter a propriedade `eat`.
|
||||
|
||||
```js
|
||||
assert(!Cat.prototype.hasOwnProperty('eat'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dae367417b2b2512b7c
|
||||
title: Use Prototype Properties to Reduce Duplicate Code
|
||||
title: Use Propriedades de Protótipos para Reduzir Código Duplicado
|
||||
challengeType: 1
|
||||
forumTopicId: 301336
|
||||
dashedName: use-prototype-properties-to-reduce-duplicate-code
|
||||
@ -8,44 +8,44 @@ dashedName: use-prototype-properties-to-reduce-duplicate-code
|
||||
|
||||
# --description--
|
||||
|
||||
Since `numLegs` will probably have the same value for all instances of `Bird`, you essentially have a duplicated variable `numLegs` inside each `Bird` instance.
|
||||
Já que `numLegs` provavelmente terá o mesmo valor para todas as instâncias de `Bird`, você tem a variável `numLegs` duplicada dentro de cada instância de `Bird`.
|
||||
|
||||
This may not be an issue when there are only two instances, but imagine if there are millions of instances. That would be a lot of duplicated variables.
|
||||
Isso pode não ser um problema quando há apenas duas instâncias, mas imagine se há milhões de instâncias. Neste cenário teríamos muitas variáveis duplicadas.
|
||||
|
||||
A better way is to use the `prototype` of `Bird`. Properties in the `prototype` are shared among ALL instances of `Bird`. Here's how to add `numLegs` to the `Bird prototype`:
|
||||
Uma maneira melhor é usar o `prototype` de `Bird`. Propriedades dentro de `prototype` são compartilhados entre todas as instâncias de `Bird`. Aqui está como adicionar `numLegs` para o `prototype` de `Bird`:
|
||||
|
||||
```js
|
||||
Bird.prototype.numLegs = 2;
|
||||
```
|
||||
|
||||
Now all instances of `Bird` have the `numLegs` property.
|
||||
Agora todas as instâncias de `Bird` possuem a propriedade `numLegs`.
|
||||
|
||||
```js
|
||||
console.log(duck.numLegs);
|
||||
console.log(canary.numLegs);
|
||||
```
|
||||
|
||||
Since all instances automatically have the properties on the `prototype`, think of a `prototype` as a "recipe" for creating objects. Note that the `prototype` for `duck` and `canary` is part of the `Bird` constructor as `Bird.prototype`. Nearly every object in JavaScript has a `prototype` property which is part of the constructor function that created it.
|
||||
Já que todas as instâncias automaticamente possuem as propriedades no `prototype`, pense no `prototype` como uma "receita" para criar objetos. Note que o `prototype` para `duck` e `canary` faz parte do construtor de `Bird` como `Bird.prototype`. Quase todos objetos em JavaScript possuem a propriedade `prototype` o qual é parte da função construtora que o criou.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a `numLegs` property to the `prototype` of `Dog`
|
||||
Adicione a propriedade `numLegs` para o `prototype` de `Dog`
|
||||
|
||||
# --hints--
|
||||
|
||||
`beagle` should have a `numLegs` property.
|
||||
`beagle` deve ter a propriedade `numLegs`.
|
||||
|
||||
```js
|
||||
assert(beagle.numLegs !== undefined);
|
||||
```
|
||||
|
||||
`beagle.numLegs` should be a number.
|
||||
`beagle.numLegs` deve ser um número.
|
||||
|
||||
```js
|
||||
assert(typeof beagle.numLegs === 'number');
|
||||
```
|
||||
|
||||
`numLegs` should be a `prototype` property not an own property.
|
||||
`numLegs` deve ser uma propriedade `prototype` e não uma propriedade própria (own property).
|
||||
|
||||
```js
|
||||
assert(beagle.hasOwnProperty('numLegs') === false);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dae367417b2b2512b7a
|
||||
title: Verify an Object's Constructor with instanceof
|
||||
title: Verifique o Construtor de um Objeto com instanceof
|
||||
challengeType: 1
|
||||
forumTopicId: 301337
|
||||
dashedName: verify-an-objects-constructor-with-instanceof
|
||||
@ -8,7 +8,7 @@ dashedName: verify-an-objects-constructor-with-instanceof
|
||||
|
||||
# --description--
|
||||
|
||||
Anytime a constructor function creates a new object, that object is said to be an <dfn>instance</dfn> of its constructor. JavaScript gives a convenient way to verify this with the `instanceof` operator. `instanceof` allows you to compare an object to a constructor, returning `true` or `false` based on whether or not that object was created with the constructor. Here's an example:
|
||||
Toda vez que a função construtora cria um novo objeto, o objeto é definido como uma <dfn>instance</dfn> do seu construtor. JavaScript provê uma forma conveniente para verificar isso com o operador `instanceof`. `instanceof` permite que você compare um objeto a um construtor, retornando `true` ou `false` caso seja ou não um objeto criado pelo construtor, respectivamente. Aqui está um exemplo:
|
||||
|
||||
```js
|
||||
let Bird = function(name, color) {
|
||||
@ -22,9 +22,9 @@ let crow = new Bird("Alexis", "black");
|
||||
crow instanceof Bird;
|
||||
```
|
||||
|
||||
This `instanceof` method would return `true`.
|
||||
Este método `instanceof` irá retornar `true`.
|
||||
|
||||
If an object is created without using a constructor, `instanceof` will verify that it is not an instance of that constructor:
|
||||
Se um objeto for criado sem usar um construtor, `instanceof` verificará que não é uma instância daquele construtor:
|
||||
|
||||
```js
|
||||
let canary = {
|
||||
@ -36,21 +36,21 @@ let canary = {
|
||||
canary instanceof Bird;
|
||||
```
|
||||
|
||||
This `instanceof` method would return `false`.
|
||||
Este método `instanceof` irá retornar `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a new instance of the `House` constructor, calling it `myHouse` and passing a number of bedrooms. Then, use `instanceof` to verify that it is an instance of `House`.
|
||||
Crie uma nova instância do construtor `House`, atribuindo à variável `myHouse` e passe o número de quartos. Então, utilize `instanceof` para verificar que é uma instância de `House`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myHouse` should have a `numBedrooms` attribute set to a number.
|
||||
`myHouse` deve ter o atributo `numBedrooms` definido para um número.
|
||||
|
||||
```js
|
||||
assert(typeof myHouse.numBedrooms === 'number');
|
||||
```
|
||||
|
||||
You should verify that `myHouse` is an instance of `House` using the `instanceof` operator.
|
||||
Você deve verificar que `myHouse` é uma instância de `House` utilizando o operador `instanceof`.
|
||||
|
||||
```js
|
||||
assert(/myHouse\s*instanceof\s*House/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dba367417b2b2512ba8
|
||||
title: Check for All or None
|
||||
title: Verificando existência
|
||||
challengeType: 1
|
||||
forumTopicId: 301338
|
||||
dashedName: check-for-all-or-none
|
||||
@ -8,11 +8,11 @@ dashedName: check-for-all-or-none
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes the patterns you want to search for may have parts of it that may or may not exist. However, it may be important to check for them nonetheless.
|
||||
Haverá vezes em que você procurará padrões que podem ou não existir na string. Pode ser relevante validá-los dependendo da situação.
|
||||
|
||||
You can specify the possible existence of an element with a question mark, `?`. This checks for zero or one of the preceding element. You can think of this symbol as saying the previous element is optional.
|
||||
Você pode fazer com que um padrão seja opcional ao usar uma interrogação, `?`, depois dele. Ela valida se há uma ou nenhuma ocorrência do padrão. Pode-se dizer que a interrogação torna o elemento à esquerda dela opcional.
|
||||
|
||||
For example, there are slight differences in American and British English and you can use the question mark to match both spellings.
|
||||
Por exemplo, com a interrogação você pode capturar palavras em inglês escritas com a ortografia americana ou britânica.
|
||||
|
||||
```js
|
||||
let american = "color";
|
||||
@ -22,36 +22,36 @@ rainbowRegex.test(american);
|
||||
rainbowRegex.test(british);
|
||||
```
|
||||
|
||||
Both uses of the `test` method would return `true`.
|
||||
Ambas as chamadas ao método `test` retornam `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the regex `favRegex` to match both the American English (`favorite`) and the British English (`favourite`) version of the word.
|
||||
Altere a regex `favRegex` para encontrar as versões americana (`favorite`) e britânica (`favourite`) da palavra.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should use the optional symbol, `?`.
|
||||
Sua regex deve usar a interrogação (`?`) para validação opcional.
|
||||
|
||||
```js
|
||||
favRegex.lastIndex = 0;
|
||||
assert(favRegex.source.match(/\?/).length > 0);
|
||||
```
|
||||
|
||||
Your regex should match the string `favorite`
|
||||
Sua regex deve encontrar a string `favorite`
|
||||
|
||||
```js
|
||||
favRegex.lastIndex = 0;
|
||||
assert(favRegex.test('favorite'));
|
||||
```
|
||||
|
||||
Your regex should match the string `favourite`
|
||||
Sua regex deve encontrar a string `favourite`
|
||||
|
||||
```js
|
||||
favRegex.lastIndex = 0;
|
||||
assert(favRegex.test('favourite'));
|
||||
```
|
||||
|
||||
Your regex should not match the string `fav`
|
||||
Sua regex não deve encontrar a string `fav`
|
||||
|
||||
```js
|
||||
favRegex.lastIndex = 0;
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5c3dda8b4d8df89bea71600f
|
||||
title: Check For Mixed Grouping of Characters
|
||||
title: Validando Grupos Mistos de Caracteres
|
||||
challengeType: 1
|
||||
forumTopicId: 301339
|
||||
dashedName: check-for-mixed-grouping-of-characters
|
||||
@ -8,11 +8,11 @@ dashedName: check-for-mixed-grouping-of-characters
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes we want to check for groups of characters using a Regular Expression and to achieve that we use parentheses `()`.
|
||||
Há vezes em que queremos validar grupos de caracteres em uma expressão regular. É possível fazê-lo usando parênteses: `()`.
|
||||
|
||||
If you want to find either `Penguin` or `Pumpkin` in a string, you can use the following Regular Expression: `/P(engu|umpk)in/g`
|
||||
Você pode usar a expressão regular `/P(engu|umpk)in/g` para encontrar tanto `Penguin` quanto `Pumpkin` em uma string.
|
||||
|
||||
Then check whether the desired string groups are in the test string by using the `test()` method.
|
||||
Depois é só usar o método `test()` para verificar se os grupos estão presentes na string.
|
||||
|
||||
```js
|
||||
let testStr = "Pumpkin";
|
||||
@ -20,51 +20,51 @@ let testRegex = /P(engu|umpk)in/;
|
||||
testRegex.test(testStr);
|
||||
```
|
||||
|
||||
The `test` method here would return `true`.
|
||||
O método `test` retorna `true` aqui.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the regex so that it checks for the names of `Franklin Roosevelt` or `Eleanor Roosevelt` in a case sensitive manner and it should make concessions for middle names.
|
||||
Corrija a regex para que ela valide os nomes `Franklin Roosevelt` e `Eleanor Roosevelt` levando em conta maiúsculas e minúsculas. A regex também deve permitir nomes do meio.
|
||||
|
||||
Then fix the code so that the regex that you have created is checked against `myString` and either `true` or `false` is returned depending on whether the regex matches.
|
||||
Depois corrija o código, fazendo com que a regex seja testada na string `myString`, retornando `true` ou `false`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex `myRegex` should return `true` for the string `Franklin D. Roosevelt`
|
||||
Sua regex `myRegex` deve retornar `true` para a string `Franklin D. Roosevelt`
|
||||
|
||||
```js
|
||||
myRegex.lastIndex = 0;
|
||||
assert(myRegex.test('Franklin D. Roosevelt'));
|
||||
```
|
||||
|
||||
Your regex `myRegex` should return `true` for the string `Eleanor Roosevelt`
|
||||
Sua regex `myRegex` deve retornar `true` para a string `Eleanor Roosevelt`
|
||||
|
||||
```js
|
||||
myRegex.lastIndex = 0;
|
||||
assert(myRegex.test('Eleanor Roosevelt'));
|
||||
```
|
||||
|
||||
Your regex `myRegex` should return `false` for the string `Franklin Rosevelt`
|
||||
Sua regex `myRegex` deve retornar `false` para a string `Franklin Rosevelt`
|
||||
|
||||
```js
|
||||
myRegex.lastIndex = 0;
|
||||
assert(!myRegex.test('Franklin Rosevelt'));
|
||||
```
|
||||
|
||||
Your regex `myRegex` should return `false` for the string `Frank Roosevelt`
|
||||
Sua regex `myRegex` deve retornar `false` para a string `Frank Roosevelt`
|
||||
|
||||
```js
|
||||
myRegex.lastIndex = 0;
|
||||
assert(!myRegex.test('Frank Roosevelt'));
|
||||
```
|
||||
|
||||
You should use `.test()` to test the regex.
|
||||
Você deve usar `.test()` para testar a regex.
|
||||
|
||||
```js
|
||||
assert(code.match(/myRegex.test\(\s*myString\s*\)/));
|
||||
```
|
||||
|
||||
Your result should return `true`.
|
||||
O resultado deve ser `true`.
|
||||
|
||||
```js
|
||||
assert(result === true);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db4367417b2b2512b92
|
||||
title: Extract Matches
|
||||
title: Extraindo Resultados
|
||||
challengeType: 1
|
||||
forumTopicId: 301340
|
||||
dashedName: extract-matches
|
||||
@ -8,11 +8,11 @@ dashedName: extract-matches
|
||||
|
||||
# --description--
|
||||
|
||||
So far, you have only been checking if a pattern exists or not within a string. You can also extract the actual matches you found with the `.match()` method.
|
||||
Até agora, você só tem verificado se existe ou não um padrão dentro de uma string. Você também pode extrair os resultados encontrados por meio do método `.match()`.
|
||||
|
||||
To use the `.match()` method, apply the method on a string and pass in the regex inside the parentheses.
|
||||
Para usar o método `.match()`, aplique o método em uma string e passe a regex dentro dos parênteses.
|
||||
|
||||
Here's an example:
|
||||
Um exemplo:
|
||||
|
||||
```js
|
||||
"Hello, World!".match(/Hello/);
|
||||
@ -21,9 +21,9 @@ let ourRegex = /expressions/;
|
||||
ourStr.match(ourRegex);
|
||||
```
|
||||
|
||||
Here the first `match` would return `["Hello"]` and the second would return `["expressions"]`.
|
||||
Aqui, o primeiro `match` retorna `["Hello"]` e, o segundo, `["expressions"]`.
|
||||
|
||||
Note that the `.match` syntax is the "opposite" of the `.test` method you have been using thus far:
|
||||
Note que o método `.match` se usa de forma "contrária" ao método `.test` que você usou até então:
|
||||
|
||||
```js
|
||||
'string'.match(/regex/);
|
||||
@ -32,23 +32,23 @@ Note that the `.match` syntax is the "opposite" of the `.test` method you have b
|
||||
|
||||
# --instructions--
|
||||
|
||||
Apply the `.match()` method to extract the string `coding`.
|
||||
Aplique o método `.match()` para extrair a string `coding`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `result` should have the string `coding`
|
||||
O resultado, `result`, deve conter a string `coding`
|
||||
|
||||
```js
|
||||
assert(result.join() === 'coding');
|
||||
```
|
||||
|
||||
Your regex `codingRegex` should search for the string `coding`
|
||||
Sua regex `codingRegex` deve buscar a string `coding`
|
||||
|
||||
```js
|
||||
assert(codingRegex.source === 'coding');
|
||||
```
|
||||
|
||||
You should use the `.match()` method.
|
||||
Você deve usar o método `.match()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.match\(.*\)/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db6367417b2b2512b9b
|
||||
title: Find Characters with Lazy Matching
|
||||
title: Encontre Caracteres com Captura Preguiçosa
|
||||
challengeType: 1
|
||||
forumTopicId: 301341
|
||||
dashedName: find-characters-with-lazy-matching
|
||||
@ -8,35 +8,35 @@ dashedName: find-characters-with-lazy-matching
|
||||
|
||||
# --description--
|
||||
|
||||
In regular expressions, a <dfn>greedy</dfn> match finds the longest possible part of a string that fits the regex pattern and returns it as a match. The alternative is called a <dfn>lazy</dfn> match, which finds the smallest possible part of the string that satisfies the regex pattern.
|
||||
Em expressões regulares, uma captura <dfn>gananciosa</dfn> encontra a parte mais longa o possível de uma string em que a regex atua e a retorna como resultado. A alternativa se chama captura <dfn>preguiçosa</dfn> e ela encontra o menor pedaço o possível de uma string que satisfaz a regex.
|
||||
|
||||
You can apply the regex `/t[a-z]*i/` to the string `"titanic"`. This regex is basically a pattern that starts with `t`, ends with `i`, and has some letters in between.
|
||||
Você pode aplicar a regex `/t[a-z]*i/` à string `"titanic"`. Essa regex é basicamente um padrão que começa com `t`, termina com `i`e tem algumas letras no meio delas.
|
||||
|
||||
Regular expressions are by default greedy, so the match would return `["titani"]`. It finds the largest sub-string possible to fit the pattern.
|
||||
Expressões regulares são gananciosas por padrão, então o resultado seria `["titani"]`. Ou seja, a maior string o possível que atende ao padrão é encontrada.
|
||||
|
||||
However, you can use the `?` character to change it to lazy matching. `"titanic"` matched against the adjusted regex of `/t[a-z]*?i/` returns `["ti"]`.
|
||||
Mas você pode usar o caractere `?` para torná-la preguiçosa. Aplicar a regex adaptada `/t[a-z]*?i/` à string `"titanic"` retorna `["ti"]`.
|
||||
|
||||
**Note:** Parsing HTML with regular expressions should be avoided, but pattern matching an HTML string with regular expressions is completely fine.
|
||||
**Obs:** Ler HTML com expressões regulares deve ser evitado, mas procurar uma string HTML usando expressões regulares é perfeitamente aceitável.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the regex `/<.*>/` to return the HTML tag `<h1>` and not the text `"<h1>Winter is coming</h1>"`. Remember the wildcard `.` in a regular expression matches any character.
|
||||
Arrume a regex `/<.*>/` para que retorne a tag HTML `<h1>` mas não a linha `"<h1>Winter is coming</h1>"`. Lembre-se de que o caractere curinga `.` em uma expressão regular captura qualquer caractere.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `result` variable should be an array with `<h1>` in it
|
||||
A variável `result` deve ser um array contendo `<h1>`
|
||||
|
||||
```js
|
||||
assert(result[0] == '<h1>');
|
||||
```
|
||||
|
||||
`myRegex` should use lazy matching
|
||||
`myRegex` deve ser preguiçosa
|
||||
|
||||
```js
|
||||
assert(/\?/g.test(myRegex));
|
||||
```
|
||||
|
||||
`myRegex` should not include the string `h1`
|
||||
`myRegex` não deve incluir a string `h1`
|
||||
|
||||
```js
|
||||
assert(!myRegex.source.match('h1'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db4367417b2b2512b93
|
||||
title: Find More Than the First Match
|
||||
title: Encontre Mais do que o Primeiro Resultado
|
||||
challengeType: 1
|
||||
forumTopicId: 301342
|
||||
dashedName: find-more-than-the-first-match
|
||||
@ -8,7 +8,7 @@ dashedName: find-more-than-the-first-match
|
||||
|
||||
# --description--
|
||||
|
||||
So far, you have only been able to extract or search a pattern once.
|
||||
Até agora você foi capaz apenas de extrair ou buscar um resultado de uma vez.
|
||||
|
||||
```js
|
||||
let testStr = "Repeat, Repeat, Repeat";
|
||||
@ -16,39 +16,39 @@ let ourRegex = /Repeat/;
|
||||
testStr.match(ourRegex);
|
||||
```
|
||||
|
||||
Here `match` would return `["Repeat"]`.
|
||||
`match` retorna `["Repeat"]` aqui.
|
||||
|
||||
To search or extract a pattern more than once, you can use the `g` flag.
|
||||
Para buscar ou extrair um padrão além do primeiro resultado, você pode usar a flag `g` (de "global").
|
||||
|
||||
```js
|
||||
let repeatRegex = /Repeat/g;
|
||||
testStr.match(repeatRegex);
|
||||
```
|
||||
|
||||
And here `match` returns the value `["Repeat", "Repeat", "Repeat"]`
|
||||
Aqui, `match` retorna o valor `["Repeat", "Repeat", "Repeat"]`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Using the regex `starRegex`, find and extract both `Twinkle` words from the string `twinkleStar`.
|
||||
Usando a regex `starRegex`, encontre e extraia ambas ocorrências da palavra `Twinkle` da string `twinkleStar`.
|
||||
|
||||
**Note**
|
||||
You can have multiple flags on your regex like `/search/gi`
|
||||
**Obs:**
|
||||
Você pode usar múltiplas flags em uma regex: `/search/gi`
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex `starRegex` should use the global flag `g`
|
||||
Sua regex `starRegex` deve usar a flag `g`
|
||||
|
||||
```js
|
||||
assert(starRegex.flags.match(/g/).length == 1);
|
||||
```
|
||||
|
||||
Your regex `starRegex` should use the case insensitive flag `i`
|
||||
Sua regex `starRegex` deve usar a flag de ignorar caixa, `i`
|
||||
|
||||
```js
|
||||
assert(starRegex.flags.match(/i/).length == 1);
|
||||
```
|
||||
|
||||
Your match should match both occurrences of the word `Twinkle`
|
||||
Seu resultado deve conter ambas as ocorrências da palavra `Twinkle`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -60,7 +60,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your match `result` should have two elements in it.
|
||||
Seu resultado, `result`, deve conter dois elementos.
|
||||
|
||||
```js
|
||||
assert(result.length == 2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db7367417b2b2512b9c
|
||||
title: Find One or More Criminals in a Hunt
|
||||
title: Encontre Um ou Mais Criminosos em uma Caçada
|
||||
challengeType: 1
|
||||
forumTopicId: 301343
|
||||
dashedName: find-one-or-more-criminals-in-a-hunt
|
||||
@ -8,11 +8,11 @@ dashedName: find-one-or-more-criminals-in-a-hunt
|
||||
|
||||
# --description--
|
||||
|
||||
Time to pause and test your new regex writing skills. A group of criminals escaped from jail and ran away, but you don't know how many. However, you do know that they stay close together when they are around other people. You are responsible for finding all of the criminals at once.
|
||||
Hora de testar as suas novas habilidades de regex. Um grupo de criminosos escapou da prisão, mas não sabemos quantos. No entanto, sabemos que eles ficam juntos quando estão no meio de outras pessoas. E você ficou responsável por encontrar todos eles.
|
||||
|
||||
Here's an example to review how to do this:
|
||||
Vamos revisitar maneiras de executar essa tarefa:
|
||||
|
||||
The regex `/z+/` matches the letter `z` when it appears one or more times in a row. It would find matches in all of the following strings:
|
||||
A regex `/z+/` encontra a letra `z` quando ela aparece uma ou mais vezes seguidas. Ela encontra resultados em todas essas strings:
|
||||
|
||||
```js
|
||||
"z"
|
||||
@ -22,7 +22,7 @@ The regex `/z+/` matches the letter `z` when it appears one or more times in a r
|
||||
"abczzzzzzzzzzzzzzzzzzzzzabc"
|
||||
```
|
||||
|
||||
But it does not find matches in the following strings since there are no letter `z` characters:
|
||||
Mas ela não encontra nada nessas strings, que não possuem `z` em lugar nenhum:
|
||||
|
||||
```js
|
||||
""
|
||||
@ -32,23 +32,23 @@ But it does not find matches in the following strings since there are no letter
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a greedy regex that finds one or more criminals within a group of other people. A criminal is represented by the capital letter `C`.
|
||||
Escreva uma regex gananciosa que encontra uma ou mais criminosos em um grupo de pessoas. Um criminoso pode ser identificado pela letra maiúscula `C`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should match one criminal (`C`) in the string `C`
|
||||
Sua regex deve encontrar um criminoso (`C`) na string `C`
|
||||
|
||||
```js
|
||||
assert('C'.match(reCriminals) && 'C'.match(reCriminals)[0] == 'C');
|
||||
```
|
||||
|
||||
Your regex should match two criminals (`CC`) in the string `CC`
|
||||
Sua regex deve encontrar dois criminosos (`CC`) na string `CC`
|
||||
|
||||
```js
|
||||
assert('CC'.match(reCriminals) && 'CC'.match(reCriminals)[0] == 'CC');
|
||||
```
|
||||
|
||||
Your regex should match three criminals (`CCC`) in the string `P1P5P4CCCcP2P6P3`.
|
||||
Sua regex deve encontrar três criminosos (`CCC`) na string `P1P5P4CCCcP2P6P3`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -57,7 +57,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should match five criminals (`CCCCC`) in the string `P6P2P7P4P5CCCCCP3P1`
|
||||
Sua regex deve encontrar cinco criminosos (`CCCCC`) na string `P6P2P7P4P5CCCCCP3P1`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -66,19 +66,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should not match any criminals in the empty string `""`
|
||||
Sua regex não deve encontrar nenhum criminoso na string vazia `""`
|
||||
|
||||
```js
|
||||
assert(!reCriminals.test(''));
|
||||
```
|
||||
|
||||
Your regex should not match any criminals in the string `P1P2P3`
|
||||
Sua regex não deve encontrar nenhum criminoso na string `P1P2P3`
|
||||
|
||||
```js
|
||||
assert(!reCriminals.test('P1P2P3'));
|
||||
```
|
||||
|
||||
Your regex should match fifty criminals (`CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC`) in the string `P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3`.
|
||||
Sua regex deve encontrar cinquenta criminosos (`CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC`) na string `P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db4367417b2b2512b91
|
||||
title: Ignore Case While Matching
|
||||
title: Ignore a Caixa ao Buscar
|
||||
challengeType: 1
|
||||
forumTopicId: 301344
|
||||
dashedName: ignore-case-while-matching
|
||||
@ -8,73 +8,73 @@ dashedName: ignore-case-while-matching
|
||||
|
||||
# --description--
|
||||
|
||||
Up until now, you've looked at regexes to do literal matches of strings. But sometimes, you might want to also match case differences.
|
||||
Até agora você escreveu regexes para encontrar strings literais. Mas, às vezes, você pode querer encontrar caixas diferentes.
|
||||
|
||||
Case (or sometimes letter case) is the difference between uppercase letters and lowercase letters. Examples of uppercase are `A`, `B`, and `C`. Examples of lowercase are `a`, `b`, and `c`.
|
||||
Caixa (-alta ou -baixa) é a diferença entre letras maiúsculas e minúsculas. São exemplos de caixa alta: `A`, `B` e `C`. `a`, `b` e `c` são exemplos de caixa baixa.
|
||||
|
||||
You can match both cases using what is called a flag. There are other flags but here you'll focus on the flag that ignores case - the `i` flag. You can use it by appending it to the regex. An example of using this flag is `/ignorecase/i`. This regex can match the strings `ignorecase`, `igNoreCase`, and `IgnoreCase`.
|
||||
Você pode encontrar ambas as caixas usando algo que chamamos de <dfn>flag</dfn>. Existem várias flags, mas agora nós queremos a flag que ignora a caixa - a flag `i`. Para usá-la é só colocar ao fim da regex. Por exemplo, escrever `/ignorecase/i` é uma forma. Essa regex pode encontrar as strings `ignorecase`, `igNoreCase` e `IgnoreCase` (e todas as outras combinações de maiúsculas e minúsculas).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a regex `fccRegex` to match `freeCodeCamp`, no matter its case. Your regex should not match any abbreviations or variations with spaces.
|
||||
Escreva uma regex `fccRegex` que encontre `freeCodeCamp`, não importa em que caixa esteja. Sua regex não deve buscar abreviações ou variações com espaços.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should match the string `freeCodeCamp`
|
||||
Sua regex deve encontrar a string `freeCodeCamp`
|
||||
|
||||
```js
|
||||
assert(fccRegex.test('freeCodeCamp'));
|
||||
```
|
||||
|
||||
Your regex should match the string `FreeCodeCamp`
|
||||
Sua regex deve encontrar a string `FreeCodeCamp`
|
||||
|
||||
```js
|
||||
assert(fccRegex.test('FreeCodeCamp'));
|
||||
```
|
||||
|
||||
Your regex should match the string `FreecodeCamp`
|
||||
Sua regex deve encontrar a string `FreecodeCamp`
|
||||
|
||||
```js
|
||||
assert(fccRegex.test('FreecodeCamp'));
|
||||
```
|
||||
|
||||
Your regex should match the string `FreeCodecamp`
|
||||
Sua regex deve encontrar a string `FreeCodecamp`
|
||||
|
||||
```js
|
||||
assert(fccRegex.test('FreeCodecamp'));
|
||||
```
|
||||
|
||||
Your regex should not match the string `Free Code Camp`
|
||||
Sua regex não deve encontrar a string `Free Code Camp`
|
||||
|
||||
```js
|
||||
assert(!fccRegex.test('Free Code Camp'));
|
||||
```
|
||||
|
||||
Your regex should match the string `FreeCOdeCamp`
|
||||
Sua regex deve encontrar a string `FreeCOdeCamp`
|
||||
|
||||
```js
|
||||
assert(fccRegex.test('FreeCOdeCamp'));
|
||||
```
|
||||
|
||||
Your regex should not match the string `FCC`
|
||||
Sua regex não deve encontrar a string `FCC`
|
||||
|
||||
```js
|
||||
assert(!fccRegex.test('FCC'));
|
||||
```
|
||||
|
||||
Your regex should match the string `FrEeCoDeCamp`
|
||||
Sua regex deve encontrar a string `FrEeCoDeCamp`
|
||||
|
||||
```js
|
||||
assert(fccRegex.test('FrEeCoDeCamp'));
|
||||
```
|
||||
|
||||
Your regex should match the string `FrEeCodECamp`
|
||||
Sua regex deve encontrar a string `FrEeCodECamp`
|
||||
|
||||
```js
|
||||
assert(fccRegex.test('FrEeCodECamp'));
|
||||
```
|
||||
|
||||
Your regex should match the string `FReeCodeCAmp`
|
||||
Sua regex deve encontrar a string `FReeCodeCAmp`
|
||||
|
||||
```js
|
||||
assert(fccRegex.test('FReeCodeCAmp'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db4367417b2b2512b90
|
||||
title: Match a Literal String with Different Possibilities
|
||||
title: Busque uma String Literal com Diferentes Possibilidades
|
||||
challengeType: 1
|
||||
forumTopicId: 301345
|
||||
dashedName: match-a-literal-string-with-different-possibilities
|
||||
@ -8,57 +8,57 @@ dashedName: match-a-literal-string-with-different-possibilities
|
||||
|
||||
# --description--
|
||||
|
||||
Using regexes like `/coding/`, you can look for the pattern `coding` in another string.
|
||||
Ao usar regexes como `/coding/`, você pode procurar pelo padrão `coding` em strings.
|
||||
|
||||
This is powerful to search single strings, but it's limited to only one pattern. You can search for multiple patterns using the `alternation` or `OR` operator: `|`.
|
||||
Isso funciona com strings únicas, mas é limitado a apenas um padrão. Você pode procurar por múltiplos padrões usando o operador de `alternação`, ou `OU`: `|`.
|
||||
|
||||
This operator matches patterns either before or after it. For example, if you wanted to match the strings `yes` or `no`, the regex you want is `/yes|no/`.
|
||||
Este operador funciona para buscar padrões à esquerda e à direita dele. Por exemplo, se você quiser encontrar as strings `yes` ou `no`, a regex que você quer é `/yes|no/`.
|
||||
|
||||
You can also search for more than just two patterns. You can do this by adding more patterns with more `OR` operators separating them, like `/yes|no|maybe/`.
|
||||
Você pode também procurar por mais de dois padrões com este operador. É possível fazer isso ao adicionar mais instâncias do operador seguido do padrão desejado: `/yes|no|maybe/`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Complete the regex `petRegex` to match the pets `dog`, `cat`, `bird`, or `fish`.
|
||||
Complete a regex `petRegex` para encontrar os pets `dog`, `cat`, `bird`, ou `fish`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex `petRegex` should return `true` for the string `John has a pet dog.`
|
||||
Sua regex `petRegex` deve retornar `true` para a string `John has a pet dog.`
|
||||
|
||||
```js
|
||||
assert(petRegex.test('John has a pet dog.'));
|
||||
```
|
||||
|
||||
Your regex `petRegex` should return `false` for the string `Emma has a pet rock.`
|
||||
Sua regex `petRegex` deve retornar `false` para a string `Emma has a pet rock.`
|
||||
|
||||
```js
|
||||
assert(!petRegex.test('Emma has a pet rock.'));
|
||||
```
|
||||
|
||||
Your regex `petRegex` should return `true` for the string `Emma has a pet bird.`
|
||||
Sua regex `petRegex` deve retornar `true` para a string `Emma has a pet bird.`
|
||||
|
||||
```js
|
||||
assert(petRegex.test('Emma has a pet bird.'));
|
||||
```
|
||||
|
||||
Your regex `petRegex` should return `true` for the string `Liz has a pet cat.`
|
||||
Sua regex `petRegex` deve retornar `true` para a string `Liz has a pet cat.`
|
||||
|
||||
```js
|
||||
assert(petRegex.test('Liz has a pet cat.'));
|
||||
```
|
||||
|
||||
Your regex `petRegex` should return `false` for the string `Kara has a pet dolphin.`
|
||||
Sua regex `petRegex` deve retornar `false` para a string `Kara has a pet dolphin.`
|
||||
|
||||
```js
|
||||
assert(!petRegex.test('Kara has a pet dolphin.'));
|
||||
```
|
||||
|
||||
Your regex `petRegex` should return `true` for the string `Alice has a pet fish.`
|
||||
Sua regex `petRegex` deve retornar `true` para a string `Alice has a pet fish.`
|
||||
|
||||
```js
|
||||
assert(petRegex.test('Alice has a pet fish.'));
|
||||
```
|
||||
|
||||
Your regex `petRegex` should return `false` for the string `Jimmy has a pet computer.`
|
||||
Sua regex `petRegex` deve retornar `false` para a string `Jimmy has a pet computer.`
|
||||
|
||||
```js
|
||||
assert(!petRegex.test('Jimmy has a pet computer.'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db7367417b2b2512b9f
|
||||
title: Match All Letters and Numbers
|
||||
title: Capture Todas as Letras e Números
|
||||
challengeType: 1
|
||||
forumTopicId: 301346
|
||||
dashedName: match-all-letters-and-numbers
|
||||
@ -8,9 +8,9 @@ dashedName: match-all-letters-and-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
Using character classes, you were able to search for all letters of the alphabet with `[a-z]`. This kind of character class is common enough that there is a shortcut for it, although it includes a few extra characters as well.
|
||||
Ao escrever `[a-z]` você foi capaz de capturar todas as letras do alfabeto. Essa classe de caracteres é tão comum que existe uma forma reduzida de escrevê-la. Mas essa forma inclui alguns caracteres a mais.
|
||||
|
||||
The closest character class in JavaScript to match the alphabet is `\w`. This shortcut is equal to `[A-Za-z0-9_]`. This character class matches upper and lowercase letters plus numbers. Note, this character class also includes the underscore character (`_`).
|
||||
Em JavaScript, você pode usar `\w` para capturar todas as letras do alfabeto. Isso é equivalente à classe de caracteres `[A-Za-z0-9_]`. Ela captura números e letras, tanto maiúsculas quanto minúsculas. Note que o underline (`_`) também é incluído nela.
|
||||
|
||||
```js
|
||||
let longHand = /[A-Za-z0-9_]+/;
|
||||
@ -23,29 +23,29 @@ longHand.test(varNames);
|
||||
shortHand.test(varNames);
|
||||
```
|
||||
|
||||
All four of these `test` calls would return `true`.
|
||||
As quatro chamadas a `test` retornam `true`.
|
||||
|
||||
These shortcut character classes are also known as <dfn>shorthand character classes</dfn>.
|
||||
Essas formas reduzidas de classes de caracteres podem ser chamadas de <dfn>atalhos</dfn>.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the shorthand character class `\w` to count the number of alphanumeric characters in various quotes and strings.
|
||||
Use o atalho `\w` para contar o número de caracteres alfanuméricos em várias strings.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should use the global flag.
|
||||
Sua regex deve usar a flag global.
|
||||
|
||||
```js
|
||||
assert(alphabetRegexV2.global);
|
||||
```
|
||||
|
||||
Your regex should use the shorthand character `\w` to match all characters which are alphanumeric.
|
||||
Sua regex deve usar o atalho `\w` para capturar todos os caracteres alfanuméricos.
|
||||
|
||||
```js
|
||||
assert(/\\w/.test(alphabetRegexV2.source));
|
||||
```
|
||||
|
||||
Your regex should find 31 alphanumeric characters in the string `The five boxing wizards jump quickly.`
|
||||
Sua regex deve encontrar 31 caracteres alfanuméricos na string `The five boxing wizards jump quickly.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -53,7 +53,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should find 32 alphanumeric characters in the string `Pack my box with five dozen liquor jugs.`
|
||||
Sua regex deve encontrar 32 caracteres alfanuméricos na string `Pack my box with five dozen liquor jugs.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -62,7 +62,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should find 30 alphanumeric characters in the string `How vexingly quick daft zebras jump!`
|
||||
Sua regex deve encontrar 30 caracteres alfanuméricos na string `How vexingly quick daft zebras jump!`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -70,7 +70,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should find 36 alphanumeric characters in the string `123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.`
|
||||
Sua regex deve encontrar 36 caracteres alfanuméricos na string `123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db8367417b2b2512ba1
|
||||
title: Match All Non-Numbers
|
||||
title: Capture Tudo Exceto Números
|
||||
challengeType: 1
|
||||
forumTopicId: 301347
|
||||
dashedName: match-all-non-numbers
|
||||
@ -8,59 +8,59 @@ dashedName: match-all-non-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge showed how to search for digits using the shortcut `\d` with a lowercase `d`. You can also search for non-digits using a similar shortcut that uses an uppercase `D` instead.
|
||||
O último desafio mostrou como procurar dígitos usando o atalho `\d` com um `d` minúsculo. Você também pode procurar não-dígitos usando um atalho semelhante que usa um `D` maiúsculo.
|
||||
|
||||
The shortcut to look for non-digit characters is `\D`. This is equal to the character class `[^0-9]`, which looks for a single character that is not a number between zero and nine.
|
||||
O atalho para procurar não-dígitos é `\D`. Esse atalho é o mesmo que `[^0-9]`, que serve para procurar qualquer caractere que não seja um dígito de zero a nove.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the shorthand character class for non-digits `\D` to count how many non-digits are in movie titles.
|
||||
Use o atalho `\D` para contar quantos não-dígitos existem em títulos de filmes.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should use the shortcut character to match non-digit characters
|
||||
Sua regex deve usar o atalho que captura não-dígitos
|
||||
|
||||
```js
|
||||
assert(/\\D/.test(noNumRegex.source));
|
||||
```
|
||||
|
||||
Your regex should use the global flag.
|
||||
Sua regex deve usar a flag global.
|
||||
|
||||
```js
|
||||
assert(noNumRegex.global);
|
||||
```
|
||||
|
||||
Your regex should find no non-digits in the string `9`.
|
||||
Sua regex não deve encontrar nenhum não-dígito na string `9`.
|
||||
|
||||
```js
|
||||
assert('9'.match(noNumRegex) == null);
|
||||
```
|
||||
|
||||
Your regex should find 6 non-digits in the string `Catch 22`.
|
||||
Sua regex deve encontrar seis não-dígitos na string `Catch 22`.
|
||||
|
||||
```js
|
||||
assert('Catch 22'.match(noNumRegex).length == 6);
|
||||
```
|
||||
|
||||
Your regex should find 11 non-digits in the string `101 Dalmatians`.
|
||||
Sua regex deve encontrar onze não-dígitos na string `101 Dalmatians`.
|
||||
|
||||
```js
|
||||
assert('101 Dalmatians'.match(noNumRegex).length == 11);
|
||||
```
|
||||
|
||||
Your regex should find 15 non-digits in the string `One, Two, Three`.
|
||||
Sua regex deve encontrar quinze não-dígitos na string `One, Two, Three`.
|
||||
|
||||
```js
|
||||
assert('One, Two, Three'.match(noNumRegex).length == 15);
|
||||
```
|
||||
|
||||
Your regex should find 12 non-digits in the string `21 Jump Street`.
|
||||
Sua regex deve encontrar 12 não-dígitos na string `21 Jump Street`.
|
||||
|
||||
```js
|
||||
assert('21 Jump Street'.match(noNumRegex).length == 12);
|
||||
```
|
||||
|
||||
Your regex should find 17 non-digits in the string `2001: A Space Odyssey`.
|
||||
Sua regex deve encontrar dezessete não-dígitos na string `2001: A Space Odyssey`.
|
||||
|
||||
```js
|
||||
assert('2001: A Space Odyssey'.match(noNumRegex).length == 17);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5d712346c441eddfaeb5bdef
|
||||
title: Match All Numbers
|
||||
title: Capture Todos os Números
|
||||
challengeType: 1
|
||||
forumTopicId: 18181
|
||||
dashedName: match-all-numbers
|
||||
@ -8,59 +8,59 @@ dashedName: match-all-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
You've learned shortcuts for common string patterns like alphanumerics. Another common pattern is looking for just digits or numbers.
|
||||
Você aprendeu atalhos para padrões comuns de strings como alfanuméricos. Outro padrão comum é o de apenas dígitos ou números.
|
||||
|
||||
The shortcut to look for digit characters is `\d`, with a lowercase `d`. This is equal to the character class `[0-9]`, which looks for a single character of any number between zero and nine.
|
||||
O atalho para procurar caracteres numéricos é `\d`, com um `d` minúsculo. Esse atalho é o mesmo que `[0-9]`, que serve para procurar qualquer dígito de zero a nove.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the shorthand character class `\d` to count how many digits are in movie titles. Written out numbers ("six" instead of 6) do not count.
|
||||
Use o atalho `\d` para contar quantos dígitos existem em títulos de filmes. Números por extenso, como "seis" em vez de 6, não contam.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should use the shortcut character to match digit characters
|
||||
Sua regex deve usar o atalho que captura dígitos
|
||||
|
||||
```js
|
||||
assert(/\\d/.test(numRegex.source));
|
||||
```
|
||||
|
||||
Your regex should use the global flag.
|
||||
Sua regex deve usar a flag global.
|
||||
|
||||
```js
|
||||
assert(numRegex.global);
|
||||
```
|
||||
|
||||
Your regex should find 1 digit in the string `9`.
|
||||
Sua regex deve encontrar um dígito na string `9`.
|
||||
|
||||
```js
|
||||
assert('9'.match(numRegex).length == 1);
|
||||
```
|
||||
|
||||
Your regex should find 2 digits in the string `Catch 22`.
|
||||
Sua regex deve encontrar dois dígitos na string `Catch 22`.
|
||||
|
||||
```js
|
||||
assert('Catch 22'.match(numRegex).length == 2);
|
||||
```
|
||||
|
||||
Your regex should find 3 digits in the string `101 Dalmatians`.
|
||||
Sua regex deve encontrar três dígitos na string `101 Dalmatians`.
|
||||
|
||||
```js
|
||||
assert('101 Dalmatians'.match(numRegex).length == 3);
|
||||
```
|
||||
|
||||
Your regex should find no digits in the string `One, Two, Three`.
|
||||
Sua regex não deve encontrar dígito algum na string `One, Two, Three`.
|
||||
|
||||
```js
|
||||
assert('One, Two, Three'.match(numRegex) == null);
|
||||
```
|
||||
|
||||
Your regex should find 2 digits in the string `21 Jump Street`.
|
||||
Sua regex deve encontrar dois dígitos na string `21 Jump Street`.
|
||||
|
||||
```js
|
||||
assert('21 Jump Street'.match(numRegex).length == 2);
|
||||
```
|
||||
|
||||
Your regex should find 4 digits in the string `2001: A Space Odyssey`.
|
||||
Sua regex deve encontrar quatro dígitos na string `2001: A Space Odyssey`.
|
||||
|
||||
```js
|
||||
assert('2001: A Space Odyssey'.match(numRegex).length == 4);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db5367417b2b2512b94
|
||||
title: Match Anything with Wildcard Period
|
||||
title: Encontre Qualquer Coisa com o Caractere Curinga
|
||||
challengeType: 1
|
||||
forumTopicId: 301348
|
||||
dashedName: match-anything-with-wildcard-period
|
||||
@ -8,9 +8,9 @@ dashedName: match-anything-with-wildcard-period
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes you won't (or don't need to) know the exact characters in your patterns. Thinking of all words that match, say, a misspelling would take a long time. Luckily, you can save time using the wildcard character: `.`
|
||||
Haverá vezes em que você não saberá (ou não precisará saber) quais caracteres exatamente farão parte das suas regexes. Pensar em todas as palavras que capturariam, digamos, um erro ortográfico levaria muito tempo. Por sorte, você pode economizar tempo usando o caractere curinga: `.`
|
||||
|
||||
The wildcard character `.` will match any one character. The wildcard is also called `dot` and `period`. You can use the wildcard character just like any other character in the regex. For example, if you wanted to match `hug`, `huh`, `hut`, and `hum`, you can use the regex `/hu./` to match all four words.
|
||||
O caractere curinga `.` captura qualquer caractere. O curinga também pode ser chamado de `ponto`. Você pode usar o curinga como qualquer outro caractere na regex. Por exemplo, se você quiser encontrar `hug`, `huh`, `hut` ou `hum`, você pode usar a regex `/hu./` para capturar todas as quatro palavras.
|
||||
|
||||
```js
|
||||
let humStr = "I'll hum a song";
|
||||
@ -20,62 +20,62 @@ huRegex.test(humStr);
|
||||
huRegex.test(hugStr);
|
||||
```
|
||||
|
||||
Both of these `test` calls would return `true`.
|
||||
As duas chamadas a `test` retornam `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Complete the regex `unRegex` so that it matches the strings `run`, `sun`, `fun`, `pun`, `nun`, and `bun`. Your regex should use the wildcard character.
|
||||
Complete a regex `unRegex` para que ela encontre as strings `run`, `sun`, `fun`, `pun`, `nun` e `bun`. Sua regex deve usar o caractere curinga.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should use the `.test()` method.
|
||||
Você deve usar o método `.test()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.test\(.*\)/));
|
||||
```
|
||||
|
||||
You should use the wildcard character in your regex `unRegex`
|
||||
Você deve usar o caractere curinga na regex `unRegex`
|
||||
|
||||
```js
|
||||
assert(/\./.test(unRegex.source));
|
||||
```
|
||||
|
||||
Your regex `unRegex` should match `run` in the string `Let us go on a run.`
|
||||
Sua regex `unRegex` deve encontrar `run` na string `Let us go on a run.`
|
||||
|
||||
```js
|
||||
unRegex.lastIndex = 0;
|
||||
assert(unRegex.test('Let us go on a run.'));
|
||||
```
|
||||
|
||||
Your regex `unRegex` should match `sun` in the string `The sun is out today.`
|
||||
Sua regex `unRegex` deve encontrar `sun` na string `The sun is out today.`
|
||||
|
||||
```js
|
||||
unRegex.lastIndex = 0;
|
||||
assert(unRegex.test('The sun is out today.'));
|
||||
```
|
||||
|
||||
Your regex `unRegex` should match `fun` in the string `Coding is a lot of fun.`
|
||||
Sua regex `unRegex` deve encontrar `fun` na string `Coding is a lot of fun.`
|
||||
|
||||
```js
|
||||
unRegex.lastIndex = 0;
|
||||
assert(unRegex.test('Coding is a lot of fun.'));
|
||||
```
|
||||
|
||||
Your regex `unRegex` should match `pun` in the string `Seven days without a pun makes one weak.`
|
||||
Sua regex `unRegex` deve encontrar `pun` na string `Seven days without a pun makes one weak.`
|
||||
|
||||
```js
|
||||
unRegex.lastIndex = 0;
|
||||
assert(unRegex.test('Seven days without a pun makes one weak.'));
|
||||
```
|
||||
|
||||
Your regex `unRegex` should match `nun` in the string `One takes a vow to be a nun.`
|
||||
Sua regex `unRegex` deve encontrar `nun` na string `One takes a vow to be a nun.`
|
||||
|
||||
```js
|
||||
unRegex.lastIndex = 0;
|
||||
assert(unRegex.test('One takes a vow to be a nun.'));
|
||||
```
|
||||
|
||||
Your regex `unRegex` should match `bun` in the string `She got fired from the hot dog stand for putting her hair in a bun.`
|
||||
Sua regex `unRegex` deve encontrar `bun` na string `She got fired from the hot dog stand for putting her hair in a bun.`
|
||||
|
||||
```js
|
||||
unRegex.lastIndex = 0;
|
||||
@ -86,14 +86,14 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex `unRegex` should not match the string `There is a bug in my code.`
|
||||
Sua regex `unRegex` não deve incluir a string `There is a bug in my code.` no resultado
|
||||
|
||||
```js
|
||||
unRegex.lastIndex = 0;
|
||||
assert(!unRegex.test('There is a bug in my code.'));
|
||||
```
|
||||
|
||||
Your regex `unRegex` should not match the string `Catch me if you can.`
|
||||
Sua regex `unRegex` não deve incluir a string `Catch me if you can.` no resultado
|
||||
|
||||
```js
|
||||
unRegex.lastIndex = 0;
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db7367417b2b2512b9d
|
||||
title: Match Beginning String Patterns
|
||||
title: Padrões de Início de String
|
||||
challengeType: 1
|
||||
forumTopicId: 301349
|
||||
dashedName: match-beginning-string-patterns
|
||||
@ -8,9 +8,9 @@ dashedName: match-beginning-string-patterns
|
||||
|
||||
# --description--
|
||||
|
||||
Prior challenges showed that regular expressions can be used to look for a number of matches. They are also used to search for patterns in specific positions in strings.
|
||||
Desafios anteriores mostraram que expressões regulares podem ser usadas para capturar um número de resultados. Elas também podem ser usadas para procurar em posições específicas de strings.
|
||||
|
||||
In an earlier challenge, you used the caret character (`^`) inside a character set to create a negated character set in the form `[^thingsThatWillNotBeMatched]`. Outside of a character set, the caret is used to search for patterns at the beginning of strings.
|
||||
Mais cedo você usou o circunflexo (`^`) em classes de caracteres para procurar caracteres que não devem ser capturados, como em `[^caracteresQueNãoQueremos]`. Quando usados fora de classes de caracteres, o circunflexo serve para buscar a partir do começo de strings.
|
||||
|
||||
```js
|
||||
let firstString = "Ricky is first and can be found.";
|
||||
@ -20,33 +20,33 @@ let notFirst = "You can't find Ricky now.";
|
||||
firstRegex.test(notFirst);
|
||||
```
|
||||
|
||||
The first `test` call would return `true`, while the second would return `false`.
|
||||
A primeira chamada a `test` retorna `true` enquanto a segunda retorna `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the caret character in a regex to find `Cal` only in the beginning of the string `rickyAndCal`.
|
||||
Use o circunflexo em uma regex para encontrar `Cal`, mas apenas no começo da string `rickyAndCal`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should search for the string `Cal` with a capital letter.
|
||||
Sua regex deve buscar a string `Cal` com uma maiúscula.
|
||||
|
||||
```js
|
||||
assert(calRegex.source == '^Cal');
|
||||
```
|
||||
|
||||
Your regex should not use any flags.
|
||||
Sua regex não deve usar nenhuma flag.
|
||||
|
||||
```js
|
||||
assert(calRegex.flags == '');
|
||||
```
|
||||
|
||||
Your regex should match the string `Cal` at the beginning of the string.
|
||||
Sua regex deve capturar a string `Cal` no começo de uma string.
|
||||
|
||||
```js
|
||||
assert(calRegex.test('Cal and Ricky both like racing.'));
|
||||
```
|
||||
|
||||
Your regex should not match the string `Cal` in the middle of a string.
|
||||
Sua regex não deve capturar a string `Cal` no meio de uma string.
|
||||
|
||||
```js
|
||||
assert(!calRegex.test('Ricky and Cal both like racing.'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db6367417b2b2512b99
|
||||
title: Match Characters that Occur One or More Times
|
||||
title: Capture Caracteres que Aparecem Uma ou Mais Vezes Seguidas
|
||||
challengeType: 1
|
||||
forumTopicId: 301350
|
||||
dashedName: match-characters-that-occur-one-or-more-times
|
||||
@ -8,33 +8,33 @@ dashedName: match-characters-that-occur-one-or-more-times
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes, you need to match a character (or group of characters) that appears one or more times in a row. This means it occurs at least once, and may be repeated.
|
||||
Às vezes você precisa capturar um caractere, ou grupo de caracteres, que aparece uma ou mais vezes seguidas. Ou seja, que aparecem pelo menos uma vez e podem se repetir.
|
||||
|
||||
You can use the `+` character to check if that is the case. Remember, the character or pattern has to be present consecutively. That is, the character has to repeat one after the other.
|
||||
Você pode usar o caractere `+` para verificar se é o caso. Lembre-se que o caractere ou padrão precisa repetir-se consecutivamente. Ou seja, um atrás do outro.
|
||||
|
||||
For example, `/a+/g` would find one match in `abc` and return `["a"]`. Because of the `+`, it would also find a single match in `aabc` and return `["aa"]`.
|
||||
Por exemplo, `/a+/g` encontra um resultado na string `abc` e retorna `["a"]`. Mas o `+` também faz com que encontre um único resultado em `aabc` e retorne `["aa"]`.
|
||||
|
||||
If it were instead checking the string `abab`, it would find two matches and return `["a", "a"]` because the `a` characters are not in a row - there is a `b` between them. Finally, since there is no `a` in the string `bcd`, it wouldn't find a match.
|
||||
Se a string fosse `abab`, a operação retornaria `["a", "a"]` porque entre os dois `a` há um `b`. Por fim, se não houvesse nenhum `a` na string, como em `bcd`, nada seria encontrado.
|
||||
|
||||
# --instructions--
|
||||
|
||||
You want to find matches when the letter `s` occurs one or more times in `Mississippi`. Write a regex that uses the `+` sign.
|
||||
Você quer capturar as ocorrências de `s` quando acontecer uma ou mais vezes em `Mississippi`. Escreve uma regex que use o caractere `+`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex `myRegex` should use the `+` sign to match one or more `s` characters.
|
||||
Sua regex `myRegex` deve usar o caractere `+` para encontrar um ou mais `s`s.
|
||||
|
||||
```js
|
||||
assert(/\+/.test(myRegex.source));
|
||||
```
|
||||
|
||||
Your regex `myRegex` should match 2 items.
|
||||
Sua regex `myRegex` deve encontrar 2 itens.
|
||||
|
||||
```js
|
||||
assert(result.length == 2);
|
||||
```
|
||||
|
||||
The `result` variable should be an array with two matches of `ss`
|
||||
A variável `result` deve ser um array com dois `ss`
|
||||
|
||||
```js
|
||||
assert(result[0] == 'ss' && result[1] == 'ss');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db6367417b2b2512b9a
|
||||
title: Match Characters that Occur Zero or More Times
|
||||
title: Capture Caracteres que Aparecem Zero ou Mais Vezes Seguidas
|
||||
challengeType: 1
|
||||
forumTopicId: 301351
|
||||
dashedName: match-characters-that-occur-zero-or-more-times
|
||||
@ -8,9 +8,9 @@ dashedName: match-characters-that-occur-zero-or-more-times
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge used the plus `+` sign to look for characters that occur one or more times. There's also an option that matches characters that occur zero or more times.
|
||||
O último desafio fez uso do caractere `+` para buscar caracteres que ocorrem uma ou mais vezes. Existe um outro caractere que permite buscar zero ou mais ocorrências de um padrão.
|
||||
|
||||
The character to do this is the asterisk or star: `*`.
|
||||
O caractere usado para isso é o asterisco: `*`.
|
||||
|
||||
```js
|
||||
let soccerWord = "gooooooooal!";
|
||||
@ -22,39 +22,39 @@ gPhrase.match(goRegex);
|
||||
oPhrase.match(goRegex);
|
||||
```
|
||||
|
||||
In order, the three `match` calls would return the values `["goooooooo"]`, `["g"]`, and `null`.
|
||||
As três chamadas a `match` retornam, na ordem, os valores: `["goooooooo"]`, `["g"]` e `null`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
For this challenge, `chewieQuote` has been initialized as the string `Aaaaaaaaaaaaaaaarrrgh!` behind the scenes. Create a regex `chewieRegex` that uses the `*` character to match an uppercase `A` character immediately followed by zero or more lowercase `a` characters in `chewieQuote`. Your regex does not need flags or character classes, and it should not match any of the other quotes.
|
||||
Neste desafio, a string `chewieQuote` recebeu o valor `Aaaaaaaaaaaaaaaarrrgh!` por trás dos panos. Escreva uma regex, `chewieRegex`, que usa o caractere `*` para capturar um `A` maiúsculo seguido imediatamente de zero ou mais `a` minúsculos em `chewieQuote`. Sua regex não precisa de flags ou de classes de caracteres. Ela também não deve capturar nenhuma outra parte da string.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex `chewieRegex` should use the `*` character to match zero or more `a` characters.
|
||||
Sua regex `chewieRegex` deve usar o caractere `*` para encontrar zero ou mais `a`s.
|
||||
|
||||
```js
|
||||
assert(/\*/.test(chewieRegex.source));
|
||||
```
|
||||
|
||||
Your regex should match the string `A` in `chewieQuote`.
|
||||
Sua regex deve encontrar a string `A` em `chewieQuote`.
|
||||
|
||||
```js
|
||||
assert(result[0][0] === 'A');
|
||||
```
|
||||
|
||||
Your regex should match the string `Aaaaaaaaaaaaaaaa` in `chewieQuote`.
|
||||
Sua regex deve encontrar a string `Aaaaaaaaaaaaaaaa` em `chewieQuote`.
|
||||
|
||||
```js
|
||||
assert(result[0] === 'Aaaaaaaaaaaaaaaa');
|
||||
```
|
||||
|
||||
Your regex `chewieRegex` should match 16 characters in `chewieQuote`.
|
||||
Sua regex `chewieRegex` deve capturar 16 caracteres em `chewieQuote`.
|
||||
|
||||
```js
|
||||
assert(result[0].length === 16);
|
||||
```
|
||||
|
||||
Your regex should not match any characters in the string `He made a fair move. Screaming about it can't help you.`
|
||||
Sua expressão regular não deve corresponder com nenhum caractere na string `He made a fair move. Screaming about it can't help you.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -62,7 +62,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should not match any characters in the string `Let him have it. It's not wise to upset a Wookiee.`
|
||||
Sua expressão regular não deve corresponder a nenhum caractere na string `Let him have it. It's not wise to upset a Wookiee.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db7367417b2b2512b9e
|
||||
title: Match Ending String Patterns
|
||||
title: Padrões de Fim de String
|
||||
challengeType: 1
|
||||
forumTopicId: 301352
|
||||
dashedName: match-ending-string-patterns
|
||||
@ -8,9 +8,9 @@ dashedName: match-ending-string-patterns
|
||||
|
||||
# --description--
|
||||
|
||||
In the last challenge, you learned to use the caret character to search for patterns at the beginning of strings. There is also a way to search for patterns at the end of strings.
|
||||
No desafio anterior, você aprendeu a usar o circunflexo para capturar padrões no início de strings. Há também uma maneira de buscar padrões no fim de strings.
|
||||
|
||||
You can search the end of strings using the dollar sign character `$` at the end of the regex.
|
||||
Se você colocar um cifrão, `$`, no fim da regex, você pode buscar no fim de strings.
|
||||
|
||||
```js
|
||||
let theEnding = "This is a never ending story";
|
||||
@ -20,27 +20,27 @@ let noEnding = "Sometimes a story will have to end";
|
||||
storyRegex.test(noEnding);
|
||||
```
|
||||
|
||||
The first `test` call would return `true`, while the second would return `false`.
|
||||
A primeira chamada a `test` retorna `true` enquanto a segunda retorna `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the anchor character (`$`) to match the string `caboose` at the end of the string `caboose`.
|
||||
Use o cifrão (`$`) para capturar a string `caboose` no fim da string `caboose`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should search for `caboose` with the dollar sign `$` anchor in your regex.
|
||||
Você deve usar o cifrão `$` na sua regex para buscar a string `caboose`.
|
||||
|
||||
```js
|
||||
assert(lastRegex.source == 'caboose$');
|
||||
```
|
||||
|
||||
Your regex should not use any flags.
|
||||
Sua regex não deve usar nenhuma flag.
|
||||
|
||||
```js
|
||||
assert(lastRegex.flags == '');
|
||||
```
|
||||
|
||||
You should match `caboose` at the end of the string `The last car on a train is the caboose`
|
||||
Você deve capturar `caboose` no fim da string `The last car on a train is the caboose`
|
||||
|
||||
```js
|
||||
assert(lastRegex.test('The last car on a train is the caboose'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db8367417b2b2512ba0
|
||||
title: Match Everything But Letters and Numbers
|
||||
title: Capture Tudo Exceto Letras e Números
|
||||
challengeType: 1
|
||||
forumTopicId: 301353
|
||||
dashedName: match-everything-but-letters-and-numbers
|
||||
@ -8,9 +8,9 @@ dashedName: match-everything-but-letters-and-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
You've learned that you can use a shortcut to match alphanumerics `[A-Za-z0-9_]` using `\w`. A natural pattern you might want to search for is the opposite of alphanumerics.
|
||||
Você aprendeu que você pode usar um atalho para capturar alfanuméricos `[A-Za-z0-9_]` usando `\w`. Você pode querer capturar exatamente o oposto disso.
|
||||
|
||||
You can search for the opposite of the `\w` with `\W`. Note, the opposite pattern uses a capital letter. This shortcut is the same as `[^A-Za-z0-9_]`.
|
||||
Você pode capturar não-alfanuméricos usando `\W` ao invés de `\w`. Observe que o atalho usa uma maiúscula. Este atalho é o mesmo que escrever `[^A-Za-z0-9_]`.
|
||||
|
||||
```js
|
||||
let shortHand = /\W/;
|
||||
@ -20,21 +20,21 @@ numbers.match(shortHand);
|
||||
sentence.match(shortHand);
|
||||
```
|
||||
|
||||
The first `match` call would return the value `["%"]` and the second would return `["!"]`.
|
||||
A primeira chamada a `match` retorna `["%"]` enquanto o segundo retorna `["!"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the shorthand character class `\W` to count the number of non-alphanumeric characters in various quotes and strings.
|
||||
Use o atalho `\W` para contar o número de caracteres não-alfanuméricos em várias strings.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should use the global flag.
|
||||
Sua regex deve usar a flag global.
|
||||
|
||||
```js
|
||||
assert(nonAlphabetRegex.global);
|
||||
```
|
||||
|
||||
Your regex should find 6 non-alphanumeric characters in the string `The five boxing wizards jump quickly.`.
|
||||
Sua regex deve encontrar 6 caracteres não-alfanuméricos na string `The five boxing wizards jump quickly.`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -42,13 +42,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should use the shorthand character to match characters which are non-alphanumeric.
|
||||
Sua regex deve usar o atalho que captura os caracteres não-alfanuméricos.
|
||||
|
||||
```js
|
||||
assert(/\\W/.test(nonAlphabetRegex.source));
|
||||
```
|
||||
|
||||
Your regex should find 8 non-alphanumeric characters in the string `Pack my box with five dozen liquor jugs.`
|
||||
Sua regex deve encontrar 8 caracteres não-alfanuméricos na string `Pack my box with five dozen liquor jugs.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -56,7 +56,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should find 6 non-alphanumeric characters in the string `How vexingly quick daft zebras jump!`
|
||||
Sua regex deve encontrar 6 caracteres não-alfanuméricos na string `How vexingly quick daft zebras jump!`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -64,7 +64,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should find 12 non-alphanumeric characters in the string `123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.`
|
||||
Sua regex deve encontrar 12 caracteres não-alfanuméricos na string `123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db5367417b2b2512b96
|
||||
title: Match Letters of the Alphabet
|
||||
title: Capture Letras do Alfabeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301354
|
||||
dashedName: match-letters-of-the-alphabet
|
||||
@ -8,11 +8,11 @@ dashedName: match-letters-of-the-alphabet
|
||||
|
||||
# --description--
|
||||
|
||||
You saw how you can use <dfn>character sets</dfn> to specify a group of characters to match, but that's a lot of typing when you need to match a large range of characters (for example, every letter in the alphabet). Fortunately, there is a built-in feature that makes this short and simple.
|
||||
Você viu como pode usar <dfn>classes de caracteres</dfn> para especificar um grupo de caracteres para capturar. Mas você precisaria escrever muito para definir uma classe larga como, por exemplo, para capturar todas as letras do alfabeto. Felizmente há uma maneira de fazer com que elas fiquem pequenas e simples.
|
||||
|
||||
Inside a character set, you can define a range of characters to match using a hyphen character: `-`.
|
||||
Você pode usar um hífen (`-`) para definir um intervalo de caracteres para capturar dentro de uma classe.
|
||||
|
||||
For example, to match lowercase letters `a` through `e` you would use `[a-e]`.
|
||||
Por exemplo, para encontrar letras minúsculas de `a` a `e`, você pode escrever `[a-e]`.
|
||||
|
||||
```js
|
||||
let catStr = "cat";
|
||||
@ -24,29 +24,29 @@ batStr.match(bgRegex);
|
||||
matStr.match(bgRegex);
|
||||
```
|
||||
|
||||
In order, the three `match` calls would return the values `["cat"]`, `["bat"]`, and `null`.
|
||||
As três chamadas a `match` retornam, na ordem, os valores: `["cat"]`, `["bat"]` e `null`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Match all the letters in the string `quoteSample`.
|
||||
Capture todas as letras na string `quoteSample`.
|
||||
|
||||
**Note**: Be sure to match both uppercase and lowercase letters.
|
||||
**Nota:** Você quer encontrar tanto maiúsculas quanto minúsculas.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex `alphabetRegex` should match 35 items.
|
||||
Sua regex `alphabetRegex` deve encontrar 35 itens.
|
||||
|
||||
```js
|
||||
assert(result.length == 35);
|
||||
```
|
||||
|
||||
Your regex `alphabetRegex` should use the global flag.
|
||||
Você deve usar a flag global na sua regex `alphabetRegex`.
|
||||
|
||||
```js
|
||||
assert(alphabetRegex.flags.match(/g/).length == 1);
|
||||
```
|
||||
|
||||
Your regex `alphabetRegex` should use the case insensitive flag.
|
||||
Você deve usar a flag de ignorar caixa na sua regex `alphabetRegex`.
|
||||
|
||||
```js
|
||||
assert(alphabetRegex.flags.match(/i/).length == 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db3367417b2b2512b8f
|
||||
title: Match Literal Strings
|
||||
title: Correspondência de strings literais
|
||||
challengeType: 1
|
||||
forumTopicId: 301355
|
||||
dashedName: match-literal-strings
|
||||
@ -8,7 +8,7 @@ dashedName: match-literal-strings
|
||||
|
||||
# --description--
|
||||
|
||||
In the last challenge, you searched for the word `Hello` using the regular expression `/Hello/`. That regex searched for a literal match of the string `Hello`. Here's another example searching for a literal match of the string `Kevin`:
|
||||
No desafio anterior, você usou a expressão regular `/Hello/` para procurar a palavra `Hello`. Esta regex buscou a string `Hello` literalmente. No exemplo abaixo há outra busca literal, dessa vez pela string `Kevin`:
|
||||
|
||||
```js
|
||||
let testStr = "Hello, my name is Kevin.";
|
||||
@ -16,38 +16,38 @@ let testRegex = /Kevin/;
|
||||
testRegex.test(testStr);
|
||||
```
|
||||
|
||||
This `test` call will return `true`.
|
||||
Essa chamada a `test` retornará `true`.
|
||||
|
||||
Any other forms of `Kevin` will not match. For example, the regex `/Kevin/` will not match `kevin` or `KEVIN`.
|
||||
Qualquer outra forma de escrever `Kevin` não funcionará. Por exemplo, a regex `/Kevin/` não encontrará nem `kevin` e nem `KEVIN`.
|
||||
|
||||
```js
|
||||
let wrongRegex = /kevin/;
|
||||
wrongRegex.test(testStr);
|
||||
```
|
||||
|
||||
This `test` call will return `false`.
|
||||
`test` retornará `false`.
|
||||
|
||||
A future challenge will show how to match those other forms as well.
|
||||
Você verá como encontrar estas outras formas em alguns desafios futuros.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Complete the regex `waldoRegex` to find `"Waldo"` in the string `waldoIsHiding` with a literal match.
|
||||
Complete a regex `waldoRegex` para encontrar `"Waldo"` na string `waldoIsHiding` de forma literal.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex `waldoRegex` should find the string `Waldo`
|
||||
Sua regex `waldoRegex` deve encontrar a string `Waldo`
|
||||
|
||||
```js
|
||||
assert(waldoRegex.test(waldoIsHiding));
|
||||
```
|
||||
|
||||
Your regex `waldoRegex` should not search for anything else.
|
||||
Sua regex `waldoRegex` não deve buscar nada além disso.
|
||||
|
||||
```js
|
||||
assert(!waldoRegex.test('Somewhere is hiding in this text.'));
|
||||
```
|
||||
|
||||
You should perform a literal string match with your regex.
|
||||
A busca com a regex deve ser por uma string literal.
|
||||
|
||||
```js
|
||||
assert(!/\/.*\/i/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db9367417b2b2512ba4
|
||||
title: Match Non-Whitespace Characters
|
||||
title: Capture Caracteres Não-Espaço
|
||||
challengeType: 1
|
||||
forumTopicId: 18210
|
||||
dashedName: match-non-whitespace-characters
|
||||
@ -8,9 +8,9 @@ dashedName: match-non-whitespace-characters
|
||||
|
||||
# --description--
|
||||
|
||||
You learned about searching for whitespace using `\s`, with a lowercase `s`. You can also search for everything except whitespace.
|
||||
Você aprendeu a procurar por espaço em branco usando `\s` com um `s` minúsculo. Você também pode buscar tudo exceto espaços em branco.
|
||||
|
||||
Search for non-whitespace using `\S`, which is an uppercase `s`. This pattern will not match whitespace, carriage return, tab, form feed, and new line characters. You can think of it being similar to the character class `[^ \r\t\f\n\v]`.
|
||||
Busque não-espaços em branco usando `\S` com um `s` maiúsculo. Este atalho não captura espaços em branco, retorno de carro, tabulações, feeds de formulário ou quebras de linha. O atalho é equivalente à classe de caracteres `[^ \r\t\f\n\v]`.
|
||||
|
||||
```js
|
||||
let whiteSpace = "Whitespace. Whitespace everywhere!"
|
||||
@ -18,27 +18,27 @@ let nonSpaceRegex = /\S/g;
|
||||
whiteSpace.match(nonSpaceRegex).length;
|
||||
```
|
||||
|
||||
The value returned by the `.length` method would be `32`.
|
||||
O valor retornado pelo método `.length` aqui é `32`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the regex `countNonWhiteSpace` to look for multiple non-whitespace characters in a string.
|
||||
Modifique a regex `countNonWhiteSpace` para que encontre tudo exceto espaços em branco em uma string.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should use the global flag.
|
||||
Sua regex deve usar a flag global.
|
||||
|
||||
```js
|
||||
assert(countNonWhiteSpace.global);
|
||||
```
|
||||
|
||||
Your regex should use the shorthand character `\S` to match all non-whitespace characters.
|
||||
Sua regex deve usar o atalho `\S` para capturar tudo menos espaços em branco.
|
||||
|
||||
```js
|
||||
assert(/\\S/.test(countNonWhiteSpace.source));
|
||||
```
|
||||
|
||||
Your regex should find 35 non-spaces in the string `Men are from Mars and women are from Venus.`
|
||||
Sua regex deve encontrar 35 não-espaços na string `Men are from Mars and women are from Venus.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -47,13 +47,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should find 23 non-spaces in the string `Space: the final frontier.`
|
||||
Sua regex deve encontrar 23 não-espaços na string `Space: the final frontier.`
|
||||
|
||||
```js
|
||||
assert('Space: the final frontier.'.match(countNonWhiteSpace).length == 23);
|
||||
```
|
||||
|
||||
Your regex should find 21 non-spaces in the string `MindYourPersonalSpace`
|
||||
Sua regex deve encontrar 21 não-espaços na string `MindYourPersonalSpace`
|
||||
|
||||
```js
|
||||
assert('MindYourPersonalSpace'.match(countNonWhiteSpace).length == 21);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db5367417b2b2512b97
|
||||
title: Match Numbers and Letters of the Alphabet
|
||||
title: Capture Números e Letras do Alfabeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301356
|
||||
dashedName: match-numbers-and-letters-of-the-alphabet
|
||||
@ -8,11 +8,11 @@ dashedName: match-numbers-and-letters-of-the-alphabet
|
||||
|
||||
# --description--
|
||||
|
||||
Using the hyphen (`-`) to match a range of characters is not limited to letters. It also works to match a range of numbers.
|
||||
O uso do hífen (`-`) para capturar um intervalo de caracteres não é limitado a letras. Ele também funciona para capturar intervalos de números.
|
||||
|
||||
For example, `/[0-5]/` matches any number between `0` and `5`, including the `0` and `5`.
|
||||
Por exemplo, `/[0-5]/` encontra qualquer número entre `0` e `5`, incluindo ambos `0` e `5`.
|
||||
|
||||
Also, it is possible to combine a range of letters and numbers in a single character set.
|
||||
E também é possível combinar intervalos de letras e números em uma única classe de caracteres.
|
||||
|
||||
```js
|
||||
let jennyStr = "Jenny8675309";
|
||||
@ -22,23 +22,23 @@ jennyStr.match(myRegex);
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a single regex that matches a range of letters between `h` and `s`, and a range of numbers between `2` and `6`. Remember to include the appropriate flags in the regex.
|
||||
Escreva uma única regex que encontra letras entre `h` e `s` e, também, números entre `2` e `6`. Lembre-se de incluir as flags necessárias na regex.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex `myRegex` should match 17 items.
|
||||
Sua regex `myRegex` deve encontrar 17 itens.
|
||||
|
||||
```js
|
||||
assert(result.length == 17);
|
||||
```
|
||||
|
||||
Your regex `myRegex` should use the global flag.
|
||||
Você deve usar a flag global na sua regex `myRegex`.
|
||||
|
||||
```js
|
||||
assert(myRegex.flags.match(/g/).length == 1);
|
||||
```
|
||||
|
||||
Your regex `myRegex` should use the case insensitive flag.
|
||||
Você deve usar a flag de ignorar caixa na sua regex `myRegex`.
|
||||
|
||||
```js
|
||||
assert(myRegex.flags.match(/i/).length == 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db5367417b2b2512b95
|
||||
title: Match Single Character with Multiple Possibilities
|
||||
title: Capture um Único Caractere com Múltiplas Possibilidades
|
||||
challengeType: 1
|
||||
forumTopicId: 301357
|
||||
dashedName: match-single-character-with-multiple-possibilities
|
||||
@ -8,11 +8,11 @@ dashedName: match-single-character-with-multiple-possibilities
|
||||
|
||||
# --description--
|
||||
|
||||
You learned how to match literal patterns (`/literal/`) and wildcard character (`/./`). Those are the extremes of regular expressions, where one finds exact matches and the other matches everything. There are options that are a balance between the two extremes.
|
||||
Você aprendeu a capturar padrões literais (`/literal/`) e usar o caractere curinga (`/./`). Eles são os extremos das expressões regulares: um encontra o texto exato e o outro captura qualquer coisa. Existem formas de balancear esses extremos.
|
||||
|
||||
You can search for a literal pattern with some flexibility with <dfn>character classes</dfn>. Character classes allow you to define a group of characters you wish to match by placing them inside square (`[` and `]`) brackets.
|
||||
Você pode ter alguma flexibilidade ao procurar um padrão literal usando <dfn>classes de caracteres</dfn>. Classes de caracteres permitem a definição de grupos de caracteres que você quer capturar ao colocá-los entre colchetes: `[` e `]`.
|
||||
|
||||
For example, you want to match `bag`, `big`, and `bug` but not `bog`. You can create the regex `/b[aiu]g/` to do this. The `[aiu]` is the character class that will only match the characters `a`, `i`, or `u`.
|
||||
Por exemplo, se você quiser encontrar `bag`, `big` e `bug` mas não `bog`. Você pode escrever a regex `/b[aiu]g/` para isso. `[aiu]` é a classe de caracteres que só capturará `a`, `i` ou `u`.
|
||||
|
||||
```js
|
||||
let bigStr = "big";
|
||||
@ -26,41 +26,41 @@ bugStr.match(bgRegex);
|
||||
bogStr.match(bgRegex);
|
||||
```
|
||||
|
||||
In order, the four `match` calls would return the values `["big"]`, `["bag"]`, `["bug"]`, and `null`.
|
||||
As quatro chamadas a `match` retornarão os seguintes valores, nesta ordem: `["big"]`, `["bag"]`, `["bug"]` e `null`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use a character class with vowels (`a`, `e`, `i`, `o`, `u`) in your regex `vowelRegex` to find all the vowels in the string `quoteSample`.
|
||||
Use classe de caracteres de vogais (`a`, `e`, `i`, `o`, `u`) na sua regex `vowelRegex` para encontrar todas as vogais na string `quoteSample`.
|
||||
|
||||
**Note:** Be sure to match both upper- and lowercase vowels.
|
||||
**Nota:** Você quer encontrar tanto maiúsculas quanto minúsculas.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should find all 25 vowels.
|
||||
Você deve encontrar todas as 25 vogais.
|
||||
|
||||
```js
|
||||
assert(result.length == 25);
|
||||
```
|
||||
|
||||
Your regex `vowelRegex` should use a character class.
|
||||
Você deve usar uma classe de caracteres na sua regex `vowelRegex`.
|
||||
|
||||
```js
|
||||
assert(/\[.*\]/.test(vowelRegex.source));
|
||||
```
|
||||
|
||||
Your regex `vowelRegex` should use the global flag.
|
||||
Você deve usar a flag global na sua regex `vowelRegex`.
|
||||
|
||||
```js
|
||||
assert(vowelRegex.flags.match(/g/).length == 1);
|
||||
```
|
||||
|
||||
Your regex `vowelRegex` should use the case insensitive flag.
|
||||
Você deve usar a flag de ignorar caixa na sua regex `vowelRegex`.
|
||||
|
||||
```js
|
||||
assert(vowelRegex.flags.match(/i/).length == 1);
|
||||
```
|
||||
|
||||
Your regex should not match any consonants.
|
||||
Sua regex não deve encontrar nenhuma consoante.
|
||||
|
||||
```js
|
||||
assert(!/[b-df-hj-np-tv-z]/gi.test(result.join()));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db6367417b2b2512b98
|
||||
title: Match Single Characters Not Specified
|
||||
title: Capture Caracteres Não Especificados
|
||||
challengeType: 1
|
||||
forumTopicId: 301358
|
||||
dashedName: match-single-characters-not-specified
|
||||
@ -8,31 +8,31 @@ dashedName: match-single-characters-not-specified
|
||||
|
||||
# --description--
|
||||
|
||||
So far, you have created a set of characters that you want to match, but you could also create a set of characters that you do not want to match. These types of character sets are called <dfn>negated character sets</dfn>.
|
||||
Até agora você aprendeu a criar classes de caracteres para capturar caracteres específicos, mas você também pode usá-las para capturar caracteres ausentes nelas. Esse tipo de classe de caracteres é chamada <dfn>classe de caracteres negada</dfn>.
|
||||
|
||||
To create a negated character set, you place a caret character (`^`) after the opening bracket and before the characters you do not want to match.
|
||||
Para criar uma classe de caracteres negada, você só precisa colocar um acento circunflexo (`^`) depois do colchete de abertura e à esquerda dos caracteres que você quer evitar.
|
||||
|
||||
For example, `/[^aeiou]/gi` matches all characters that are not a vowel. Note that characters like `.`, `!`, `[`, `@`, `/` and white space are matched - the negated vowel character set only excludes the vowel characters.
|
||||
Por exemplo, `/[^aeiou]/gi` encontra todos os caracteres que não são vogais. Observe que caracteres como `.`, `!`, `[`, `@`, `/` e espaços em branco são capturados - a classe de vogais negada apenas exclui os caracteres que são vogais.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a single regex that matches all characters that are not a number or a vowel. Remember to include the appropriate flags in the regex.
|
||||
Crie uma única regex que captura todos os caracteres que não são números ou vogais. Lembre-se de incluir as flags necessárias na regex.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex `myRegex` should match 9 items.
|
||||
Sua regex `myRegex` deve encontrar 9 itens.
|
||||
|
||||
```js
|
||||
assert(result.length == 9);
|
||||
```
|
||||
|
||||
Your regex `myRegex` should use the global flag.
|
||||
Você deve usar a flag global na sua regex `myRegex`.
|
||||
|
||||
```js
|
||||
assert(myRegex.flags.match(/g/).length == 1);
|
||||
```
|
||||
|
||||
Your regex `myRegex` should use the case insensitive flag.
|
||||
Você deve usar a flag de ignorar caixa na sua regex `myRegex`.
|
||||
|
||||
```js
|
||||
assert(myRegex.flags.match(/i/).length == 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7db8367417b2b2512ba3
|
||||
title: Match Whitespace
|
||||
title: Capture Espaço em Branco
|
||||
challengeType: 1
|
||||
forumTopicId: 301359
|
||||
dashedName: match-whitespace
|
||||
@ -8,9 +8,9 @@ dashedName: match-whitespace
|
||||
|
||||
# --description--
|
||||
|
||||
The challenges so far have covered matching letters of the alphabet and numbers. You can also match the whitespace or spaces between letters.
|
||||
Os desafios até agora cobriram a captura de letras do alfabeto e números. Você também pode capturar espaços em branco e os espaços entre as letras.
|
||||
|
||||
You can search for whitespace using `\s`, which is a lowercase `s`. This pattern not only matches whitespace, but also carriage return, tab, form feed, and new line characters. You can think of it as similar to the character class `[ \r\t\f\n\v]`.
|
||||
Você pode usar o atalho `\s` com um `s` minúsculo para capturar espaços em branco. Este atalho não captura apenas espaços em branco como também retorno de carro, tabulações, feeds de formulário e quebras de linha. O atalho é equivalente à classe de caracteres `[ \r\t\f\n\v]`.
|
||||
|
||||
```js
|
||||
let whiteSpace = "Whitespace. Whitespace everywhere!"
|
||||
@ -18,26 +18,26 @@ let spaceRegex = /\s/g;
|
||||
whiteSpace.match(spaceRegex);
|
||||
```
|
||||
|
||||
This `match` call would return `[" ", " "]`.
|
||||
`match` retorna `[" ", " "]` aqui.
|
||||
# --instructions--
|
||||
|
||||
Change the regex `countWhiteSpace` to look for multiple whitespace characters in a string.
|
||||
Mude a regex `countWhiteSpace` para que capture múltiplos espaços em branco em strings.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your regex should use the global flag.
|
||||
Sua regex deve usar a flag global.
|
||||
|
||||
```js
|
||||
assert(countWhiteSpace.global);
|
||||
```
|
||||
|
||||
Your regex should use the shorthand character `\s` to match all whitespace characters.
|
||||
Sua regex deve usar o atalho `\s` para capturar todos os espaços em branco.
|
||||
|
||||
```js
|
||||
assert(/\\s/.test(countWhiteSpace.source));
|
||||
```
|
||||
|
||||
Your regex should find eight spaces in the string `Men are from Mars and women are from Venus.`
|
||||
Sua regex deve encontrar oito espaços na string `Men are from Mars and women are from Venus.`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -46,13 +46,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your regex should find three spaces in the string `Space: the final frontier.`
|
||||
Sua regex deve encontrar três espaços na string `Space: the final frontier.`
|
||||
|
||||
```js
|
||||
assert('Space: the final frontier.'.match(countWhiteSpace).length == 3);
|
||||
```
|
||||
|
||||
Your regex should find no spaces in the string `MindYourPersonalSpace`
|
||||
Sua regex não deve encontrar espaços na string `MindYourPersonalSpace`
|
||||
|
||||
```js
|
||||
assert('MindYourPersonalSpace'.match(countWhiteSpace) == null);
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user