fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@@ -0,0 +1,29 @@
---
title: Add Elements to the End of an Array Using concat Instead of push
localeTitle: Adicionar elementos ao final de um array usando concat Em vez de push
---
## Adicionar elementos ao final de um array usando concat Em vez de push
Onde o método `push` adiciona um novo elemento ao final do array original, o método `concat` cria um novo array contendo os elementos do array original e o novo elemento. O array original permanece o mesmo ao usar `concat` .
#### Links Relevantes:
* [Array.prototype.concat ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)
## Solução
```javascript
function nonMutatingPush(original, newItem) {
// Add your code below this line
return original.concat(newItem);
// Add your code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);
```

View File

@@ -0,0 +1,39 @@
---
title: Apply Functional Programming to Convert Strings to URL Slugs
localeTitle: Aplicar programação funcional para converter seqüências de caracteres em URL Slugs
---
## Aplicar programação funcional para converter seqüências de caracteres em URL Slugs
### Solução
```javascript
// the global variable
var globalTitle = "Winter Is Coming";
// Add your code below this line
function urlSlug(title) {
return title.split(/\W/).filter((obj)=>{
return obj !=='';
}).join('-').toLowerCase();
}
// Add your code above this line
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
```
### Solução alternativa
```javascript
// the global variable
var globalTitle = "Winter Is Coming";
// Add your code below this line
function urlSlug(title) {
return title.toLowerCase().trim().split(/\s+/).join('-');
}
// Add your code above this line
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
```

View File

@@ -0,0 +1,31 @@
---
title: Avoid Mutations and Side Effects Using Functional Programming
localeTitle: Evite Mutações e Efeitos Colaterais Usando Programação Funcional
---
## Evite Mutações e Efeitos Colaterais Usando Programação Funcional
### Explicação do Problema
Preencha o código para o `incrementer` função para que ele retorne o valor da variável global `fixedValue` aumentado em um. `fixedValue` não deve mudar, não importa quantas vezes a função `incrememter` seja chamada.
### Sugestão 1
Usar o operador de incremento ( `++` ) em `fixedValue` `fixedValue` , o que significa que ele não fará mais referência ao mesmo valor com o qual foi designado.
### Solução:
```javascript
// the global variable
var fixedValue = 4;
function incrementer () {
// Add your code below this line
return fixedValue + 1;
// Add your code above this line
}
var newValue = incrementer(); // Should equal 5
console.log(fixedValue); // Should print 4
```

View File

@@ -0,0 +1,35 @@
---
title: Combine an Array into a String Using the join Method
localeTitle: Combine uma matriz em uma seqüência de caracteres usando o método de associação
---
## Combine uma matriz em uma seqüência de caracteres usando o método de associação
### Explicação do Problema
Use o método `join` (entre outros) dentro da função `sentensify` para fazer uma sentença a partir das palavras na string `str` . A função deve retornar uma string. Por exemplo, "Eu-como-Star-Wars" seria convertido para "Eu gosto de Star Wars". Para este desafio, não use o método `replace` .
#### Links Relevantes:
* [Array.prototype.join ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)
* [String.prototype.split ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
* [Expressões regulares](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
### Dica1
Você pode precisar converter a string para um array primeiro.
### Dica2
Você pode precisar usar expressões regulares para dividir a string.
### Solução:
```javascript
function sentensify(str) {
// Add your code below this line
return str.split(/\W/).join(' ');
// Add your code above this line
}
sentensify("May-the-force-be-with-you");
```

View File

@@ -0,0 +1,24 @@
---
title: Combine Two Arrays Using the concat Method
localeTitle: Combine duas matrizes usando o método concat
---
## Combine duas matrizes usando o método concat
* O método concat é usado para unir dois ou mais arrays ou strings.
* Este método não altera os arrays existentes, mas retorna um novo array.
## Solução
```javascript
function nonMutatingConcat(original, attach) {
// Add your code below this line
return original.concat(attach);
// Add your code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingConcat(first, second);
```

View File

@@ -0,0 +1,34 @@
---
title: Implement map on a Prototype
localeTitle: Implementar mapa em um protótipo
---
## Implementar mapa em um protótipo
Para resolver este desafio usando a palavra-chave, esta é uma chave.
Isso nos dará acesso ao objeto que estamos chamando de myMap.
A partir daí, podemos usar o loop forEach ou for para adicionar elementos ao array vazio já declarado à medida que modificamos cada elemento com o método de retorno de chamada fornecido.
```javascript
// the global Array
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback){
var newArray = [];
// Add your code below this line
this.forEach(a => newArray.push(callback(a)));
// Add your code above this line
return newArray;
};
var new_s = s.myMap(function(item){
return item * 2;
});
```
### Links Úteis
[isto. Javascript MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
[isto. Javascript W3Schools](https://www.w3schools.com/js/js_this.asp)

View File

@@ -0,0 +1,45 @@
---
title: Implement the filter Method on a Prototype
localeTitle: Implementar o método de filtro em um protótipo
---
## Implementar o método de filtro em um protótipo
```javascript
// the global Array
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
this.forEach(function(x) {
if (callback(x) == true) {
newArray.push(x);
}
})
// Add your code above this line
return newArray;
};
```
## Outra solução usando o looop!
```javascript
Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
for (let i=0; i<this.length;i++){
if(callback(this[i])=== true ){
newArray.push(this[i]);
}
}
// Add your code above this line
return newArray;
};
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
```

View File

@@ -0,0 +1,11 @@
---
title: Functional Programming
localeTitle: Programação Funcional
---
## Programação Funcional
Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md) .
[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .
#### Mais Informações:

View File

@@ -0,0 +1,21 @@
---
title: Introduction to Currying and Partial Application
localeTitle: Introdução ao Currying e Aplicação Parcial
---
## Introdução ao Currying e Aplicação Parcial
### Solução
```javascript
function add(x) {
// Add your code below this line
return function(y) {
return function(z) {
return x + y + z;
}
}
// Add your code above this line
}
add(10)(20)(30);
```

View File

@@ -0,0 +1,48 @@
---
title: Learn About Functional Programming
localeTitle: Aprenda sobre a programação funcional
---
## Aprenda sobre a programação funcional
Uma função tem uma entrada ou um parâmetro `const myFunc = (input) => { ...code to execute... }` . Neste caso, a entrada é quantas xícaras de chá devem ser criadas.
### Método
Apenas uma linha de código deve ser alterada para passar esse desafio. A função `getTea()` deve ser chamada e armazenada na variável `tea4TeamFCC` . Certifique-se de ler a função `getTea()` e entender exatamente o que ela faz. A função recebe uma variável - `numOfCups` . Um array `teaCups[]` é criado primeiro e um loop for é configurado para contar o número de cups passados para a função. Uma nova xícara de chá é então empurrada para o array a cada iteração do loop for.
Assim, resultando em um array cheio da quantidade de xícaras originalmente passadas para a função `getTea()` .
### Solução
```javascript
/**
* A long process to prepare tea.
* @return {string} A cup of tea.
**/
const prepareTea = () => 'greenTea';
/**
* Get given number of cups of tea.
* @param {number} numOfCups Number of required cups of tea.
* @return {Array<string>} Given amount of tea cups.
**/
const getTea = (numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
// Add your code below this line
const tea4TeamFCC = getTea(40); // :(
// Add your code above this line
console.log(tea4TeamFCC);
```

View File

@@ -0,0 +1,32 @@
---
title: Pass Arguments to Avoid External Dependence in a Function
localeTitle: Passar Argumentos para Evitar Dependência Externa em uma Função
---
## Passar Argumentos para Evitar Dependência Externa em uma Função
## Sugestão: 1
Tente passar o argumento para funcionar e retornar um valor maior desse argumento.
**Solução à frente!**
## Solução básica de código:
```javascript
// the global variable
var fixedValue = 4;
// Add your code below this line
function incrementer (value) {
return value + 1;
// Add your code above this line
}
var newValue = incrementer(fixedValue); // Should equal 5
console.log(fixedValue); // Should print 4
```
### Método
Este código irá fornecer o mesmo resultado que o último desafio, só que desta vez vamos passar o `fixedValue` para a função como um parâmetro.

View File

@@ -0,0 +1,46 @@
---
title: Refactor Global Variables Out of Functions
localeTitle: Refatorar variáveis globais com funções
---
## Refatorar variáveis globais com funções
* Se você está tendo problemas com a mudança de bookList, tente usar uma cópia do array em suas funções.
* Aqui estão mais algumas informações sobre \[como o JavaScript lida com os argumentos de função\] (https://codeburst.io/javascript-passing-by-value-vs-reference -plicated-in-plain-english-8d00fd06a47c).
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":principiante:") Solução básica de código:
## Solução 1
```javascript
function add (arr, bookName) {
let newArr = [...arr]; // Copy the bookList array to a new array.
newArr.push(bookName); // Add bookName parameter to the end of the new array.
return newArr; // Return the new array.
}
function remove (arr, bookName) {
let newArr = [...arr]; // Copy the bookList array to a new array.
if (newArr.indexOf(bookName) >= 0) { // Check whether the bookName parameter is in new array.
/.
newArr.splice(newArr.indexOf(bookName), 1); // Remove the given paramater from the new array.
return newArr; // Return the new array.
}
}
```
## Solução 2
```javascript
function add (list,bookName) {
return [...list, bookName];
}
function remove (list,bookName) {
if (list.indexOf(bookName) >= 0) {
return list.filter((item) => item !== bookName);
}
}
```

View File

@@ -0,0 +1,24 @@
---
title: Remove Elements from an Array Using slice Instead of splice
localeTitle: Remover elementos de um array usando slice Em vez de splice
---
## Remover elementos de um array usando slice Em vez de splice
* A diferença entre o método splice e slice é que o método slice não altera o array original, mas retorna um novo.
* O método de fatia leva 2 dois argumentos para os índices começarem e terminarem a fatia (o final não é inclusivo).
* Se você não quiser alterar o array original, poderá usar o método de fatia.
## Solução
```javascript
function nonMutatingSplice(cities) {
// Add your code below this line
return cities.slice(0, 3);
// Add your code above this line
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
```

View File

@@ -0,0 +1,24 @@
---
title: Return a Sorted Array Without Changing the Original Array
localeTitle: Retornar uma matriz classificada sem alterar a matriz original
---
## Retornar uma matriz classificada sem alterar a matriz original
### Método
Em primeiro lugar concatene a matriz tomada como um parâmetro para uma nova matriz vazia. Em seguida, use o método `sort()` como visto no último desafio e crie uma função para classificar a nova matriz em ordem crescente.
### Solução
```javascript
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Add your code below this line
return [].concat(arr).sort(function(a, b) {
return a - b;
});
// Add your code above this line
}
nonMutatingSort(globalArray);
```

View File

@@ -0,0 +1,34 @@
---
title: Return Part of an Array Using the slice Method
localeTitle: Retornar parte de uma matriz usando o método de fatia
---
## Retornar parte de uma matriz usando o método de fatia
### Explicação do Problema
Use o método de fatia na função sliceArray para retornar parte do array anim dado os índices beginSlice e endSlice fornecidos. A função deve retornar uma matriz.
### Método
A função pode ser escrita simplesmente escrevendo uma linha de código - uma declaração de retorno. Assim como no exemplo dado, corte a matriz que a função usa como parâmetro usando os parâmetros `beginSlice` e `endSlice` como parâmetros para o método `slice()` . Lembre-se da estrutura do método `slice()` :
```javascript
var arr = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
arr.slice([index-to-begin-slice] , [index-to-end-slice]);
```
### Solução
```javascript
function sliceArray(anim, beginSlice, endSlice) {
// Add your code below this line
return anim.slice(beginSlice, endSlice);
// Add your code above this line
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
```
#### Links Relevantes:
* [Array.prototype.slice ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)

View File

@@ -0,0 +1,35 @@
---
title: Sort an Array Alphabetically using the sort Method
localeTitle: Ordenar uma matriz em ordem alfabética usando o método de classificação
---
## Ordenar uma matriz em ordem alfabética usando o método de classificação
### Método
No exemplo dado, vemos como escrever uma função que retornará uma nova matriz em ordem alfabética inversa.
```javascript
function reverseAlpha(arr) {
return arr.sort(function(a, b) {
return a < b;
});
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']
```
Usando essa lógica, simplesmente faça engenharia reversa da função para retornar uma nova matriz em ordem alfabética.
### Solução
```javascript
function alphabeticalOrder(arr) {
// Add your code below this line
return arr.sort(function(a,b) {
return a > b;
});
// Add your code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
```

View File

@@ -0,0 +1,23 @@
---
title: Split a String into an Array Using the split Method
localeTitle: Dividir uma string em uma matriz usando o método de divisão
---
## Dividir uma string em uma matriz usando o método de divisão
### Método
Basta dividir a string para criar uma nova matriz de palavras.
Uma expressão regular simples pode ser usada para alcançar este resultado.
### Solução
```javascript
function splitify(str) {
// Add your code below this line
return str.split(/\W/);
// Add your code above this line
}
splitify("Hello World,I-am code");
```

View File

@@ -0,0 +1,51 @@
---
title: Understand Functional Programming Terminology
localeTitle: Entenda a terminologia de programação funcional
---
## Entenda a terminologia de programação funcional
### Método
Assim como no último desafio, você deve chamar o método `getTea` e armazená-lo em uma variável. Só que desta vez, você tem 2 variáveis para armazenar 2 conjuntos separados de dados. Você verá que a função `getTea()` é a mesma de antes, só que agora leva 2 parâmetros separados. O primeiro parâmetro é uma função, portanto, precisaremos passar a função `prepareGreenTea()` ou a função `prepareBlackTea()` , seguida pelo segundo parâmetro `numOfCups` que pode ser inserido como um inteiro.
### Solução
Neste exercício, estamos atribuindo o resultado de uma função de ordem superior às variáveis. Para fazer isso, chamamos uma função com uma função de retorno de chamada como um parâmetro.
## Dica:
`javascript const basketOne = makeBasket(addFruit, 10)`
\## Solução:
\`\` \`javascript
/ \*\*
* Um longo processo para preparar o chá verde.
* @return {string} Uma xícara de chá verde. \*\* / const prepareGreenTea = () => 'greenTea';
/ \*\*
* Obter determinado número de xícaras de chá.
* @param {function (): string} prepareTea O tipo de função de preparação de chá.
* @param {number} numOfCups Número de xícaras de chá necessárias.
* @return {Matriz } Dada quantidade de xícaras de chá. \*\* / const getTea = (prepareTea, numOfCups) => { teaCups const = \[\];
para (deixar xícaras = 1; xícaras <= numOfCups; xícaras + = 1) { const teaCup = prepareTea (); teaCups.push (teaCup); }
retornar teaCups; };
// Adicione seu código abaixo desta linha const tea4GreenTeamFCC = getTea (prepareGreenTea, 27); // :) const tea4BlackTeamFCC = getTea (prepareBlackTea, 13); // :) // Adicione seu código acima desta linha
console.log ( tea4GreenTeamFCC, tea4BlackTeamFCC );
\`\` \`
## Explicação de código:
Na solução acima, passamos as funções `prepareGreenTea()` e `prepareBlackTea()` como parâmetros ou funções de retorno de chamada para as funções `getTea()` estão sendo atribuídas às nossas duas variáveis constantes `tea4BlackTeamFCC` e `tea4GreenTeamFCC` . Desta forma, nenhuma variável global é alterada e temos a opção de adicionar um número ilimitado de opções diferentes de métodos `prepareTea()` , já que é uma função de retorno de chamada passada para a função de ordem superior de `getTea()` .

View File

@@ -0,0 +1,9 @@
---
title: Understand the Hazards of Using Imperative Code
localeTitle: Entenda os perigos do uso do código imperativo
---
## Entenda os perigos do uso do código imperativo
Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code/index.md) .
[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .

View File

@@ -0,0 +1,43 @@
---
title: Use the every Method to Check that Every Element in an Array Meets a Criteria
localeTitle: Use o método Every para verificar se todos os elementos em uma matriz atendem a um critério
---
## Use o método Every para verificar se todos os elementos em uma matriz atendem a um critério
### Explicação do Problema:
Use o método `every` dentro da função `checkPositive` para verificar se todos os elementos em `arr` são positivos. A função deve retornar um valor booleano.
#### Links Relevantes:
* [Array.prototype.every ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every)
### Sugestão
Não esqueça de `return` .
## Solução
```javascript
function checkPositive(arr) {
// Add your code below this line
return arr.every(val => val > 0);
// Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```
## Solução alternativa
```javascript
function checkPositive(arr) {
// Add your code below this line
return arr.every(function(value) {
return value > 0;
});
// Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```

View File

@@ -0,0 +1,22 @@
---
title: Use the filter method to extract data from an array
localeTitle: Use o método filter para extrair dados de um array
---
## Use o método filter para extrair dados de um array
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ": speech_balloon:") Sugestão: 1
Este desafio é resolvido em 2 etapas. Primeiro, Array.prototype.filter é usado para filtrar a matriz, deixando elementos que tenham imdbRating> 8.0. Depois disso, Array.prototype.map pode ser usado para moldar a saída para o formato desejado.
### Solução
```javascript
// Add your code below this line
var filteredList = watchList.map(function(e) {
return {title: e["Title"], rating: e["imdbRating"]}
}).filter((e) => e.rating >= 8);
console.log(filteredList);
```

View File

@@ -0,0 +1,27 @@
---
title: Use the map Method to Extract Data from an Array
localeTitle: Use o método map para extrair dados de uma matriz
---
## Use o método map para extrair dados de uma matriz
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ": speech_balloon:") Sugestão: 1
array.prototype.map assume uma função como na entrada e retorna uma matriz. A matriz retornada inclui elementos que são processados pela função. Essa função usa elementos individuais como entrada.
## Alerta de Spoiler!
![sinal de aviso](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solução à frente!**
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ": rotating_light:") Solução de Código Intermediário:
```javascript
rating = watchList.map( (item) => ({"title":item["Title"], "rating":item["imdbRating"]}) );
```
\### Explicação do código: Usando a notação ES6, cada item da matriz é processado para extrair o título e a classificação. Parantheses são necessários para retornar um objeto.
#### Links Relevantes
* [Funções de seta](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

View File

@@ -0,0 +1,130 @@
---
title: Use the reduce Method to Analyze Data
localeTitle: Use o método de redução para analisar dados
---
## Use o método de redução para analisar dados
```javascript
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
// Add your code below this line
var averageRating = watchList.filter(x => x.Director === "Christopher Nolan").map(x => Number(x.imdbRating)).reduce((x1, x2) => x1 + x2) / watchList.filter(x => x.Director === "Christopher Nolan").length;
// Add your code above this line
console.log(averageRating);
```

View File

@@ -0,0 +1,23 @@
---
title: Use the some Method to Check that Any Elements in an Array Meet a Criteria
localeTitle: Use o método Some para verificar se todos os elementos em uma matriz atendem a um critério
---
## Use o método Some para verificar se todos os elementos em uma matriz atendem a um critério
### Explicação do Problema
Use o método some dentro da função checkPositive para verificar se algum elemento em arr é positivo. A função `checkPositive` deve retornar um valor booleano.
#### Links Relevantes:
* [Array.prototype.some ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
### Solução:
```javascript
function checkPositive(arr) {
return arr.some((elem) => elem > 0);
}
checkPositive([1, 2, 3, -4, 5]);
```