chore(i18n,curriculum): update translations (#42487)
* chore(i18n,curriculum): update translations * chore: Italian to italian Co-authored-by: Nicholas Carrigan <nhcarrigan@gmail.com>
This commit is contained in:
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b67
|
||||
title: Aggiungere elementi alla fine di un array usando concat invece di push
|
||||
challengeType: 1
|
||||
forumTopicId: 301226
|
||||
dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
La programmazione funzionale riguarda la creazione e l'utilizzo di funzioni non mutanti.
|
||||
|
||||
L'ultima sfida ha introdotto il metodo `concat` come modo per combinare degli array in uno nuovo senza mutare gli array originali. Confronta `concat` con il metodo `push`. `push` aggiunge un elemento alla fine dello stesso array sul quale viene richiamato, mutando quello stesso array. Ecco un esempio:
|
||||
|
||||
```js
|
||||
var arr = [1, 2, 3];
|
||||
arr.push([4, 5, 6]);
|
||||
```
|
||||
|
||||
`arr` avrà un valore modificato di `[1, 2, 3, [4, 5, 6]]`, che non è in linea con la programmazione funzionale.
|
||||
|
||||
`concat` offre un modo per aggiungere nuovi elementi alla fine di un array senza effetti collaterali di mutazione dello stesso.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Cambia la funzione `nonMutatingPush` in modo da utilizzare `concat` invece di `push` per aggiungere `newItem` alla fine di `original`. La funzione dovrebbe restituire un array.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti usare il metodo `concat`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.concat/g));
|
||||
```
|
||||
|
||||
Non dovresti usare il metodo `push`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?push/g));
|
||||
```
|
||||
|
||||
L'array `first` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
|
||||
```
|
||||
|
||||
L'array `second` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
|
||||
```
|
||||
|
||||
`nonMutatingPush([1, 2, 3], [4, 5])` dovrebbe restituire `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) ===
|
||||
JSON.stringify([1, 2, 3, 4, 5])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nonMutatingPush(original, newItem) {
|
||||
// Only change code below this line
|
||||
return original.push(newItem);
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingPush(first, second);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nonMutatingPush(original, newItem) {
|
||||
return original.concat(newItem);
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingPush(first, second);
|
||||
```
|
@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6d
|
||||
title: Applicare la programmazione funzionale per convertire le stringhe in URL Slug
|
||||
challengeType: 1
|
||||
forumTopicId: 301227
|
||||
dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Molte delle ultime sfide hanno riguardato una serie di utili metodi per gli array e le stringhe che seguono principi di programmazione funzionale. Abbiamo anche conosciuto `reduce`, che è un metodo potente utilizzato per ridurre i problemi a forme più semplici. Dalle medie di calcolo all'ordinamento, qualsiasi operazione sugli array può essere ottenuta applicandolo. Ricordiamo che `map` e `filter` sono casi speciali di `reduce`.
|
||||
|
||||
Combiniamo quello che abbiamo imparato per risolvere un problema pratico.
|
||||
|
||||
Molti siti di gestione dei contenuti (CMS) aggiungono il titolo di un post a parte del suo URL per rendere il bookmarking più semplice. Ad esempio, se scrivi un post su Medium intitolato `Stop Using Reduce`, è probabile che l'URL abbia qualche forma della stringa del titolo al suo interno (`.../stop-using-reduce`). Potresti averlo già notato sul sito freeCodeCamp.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Compila la funzione `urlSlug` in modo che converta una stringa `title` e restituisca la versione tratteggiata per l'URL. È possibile utilizzare uno qualsiasi dei metodi descritti in questa sezione, senza utilizzare `replace`. Ecco i requisiti:
|
||||
|
||||
L'input è una stringa con spazi e parole con le iniziali in maiuscolo
|
||||
|
||||
L'output è una stringa con gli spazi tra le parole sostituiti da un trattino (`-`)
|
||||
|
||||
L'output dovrebbe composto di sole lettere minuscole
|
||||
|
||||
L'output non dovrebbe avere spazi
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice non dovrebbe usare il metodo `replace` per questa sfida.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?replace/g));
|
||||
```
|
||||
|
||||
`urlSlug("Winter Is Coming")` dovrebbe restituire la stringa `winter-is-coming`.
|
||||
|
||||
```js
|
||||
assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
|
||||
```
|
||||
|
||||
`urlSlug(" Winter Is Coming")` dovrebbe restituire la stringa `winter-is-coming`.
|
||||
|
||||
```js
|
||||
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
|
||||
```
|
||||
|
||||
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` dovrebbe restituire la stringa `a-mind-needs-books-like-a-sword-needs-a-whetstone`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
urlSlug('A Mind Needs Books Like A Sword Needs A Whetstone') ===
|
||||
'a-mind-needs-books-like-a-sword-needs-a-whetstone'
|
||||
);
|
||||
```
|
||||
|
||||
`urlSlug("Hold The Door")` dovrebbe restituire la stringa `hold-the-door`.
|
||||
|
||||
```js
|
||||
assert(urlSlug('Hold The Door') === 'hold-the-door');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
function urlSlug(title) {
|
||||
|
||||
|
||||
}
|
||||
// Only change code above this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
function urlSlug(title) {
|
||||
return title.trim().split(/\s+/).join("-").toLowerCase();
|
||||
}
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5e
|
||||
title: Evitare mutazioni ed effetti collaterali utilizzando la programmazione funzionale
|
||||
challengeType: 1
|
||||
forumTopicId: 301228
|
||||
dashedName: avoid-mutations-and-side-effects-using-functional-programming
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Come avrai già capito, il problema nella sfida precedente è stato con la chiamata a `splice` nella funzione `tabClose()`. Sfortunatamente, `splice` cambia l'array su cui viene chiamato, così la seconda chiamata ad esso usava un array modificato, dando risultati inaspettati.
|
||||
|
||||
Questo è un piccolo esempio di un modello molto più grande - si chiama una funzione su una variabile, un array, o un oggetto, e la funzione cambia la variabile o qualcosa nell'oggetto.
|
||||
|
||||
Uno dei principi fondamentali della programmazione funzionale è di non cambiare le cose. Le modifiche portano a bug. È più facile prevenire i bug sapendo che le tue funzioni non cambiano nulla, inclusi gli argomenti delle funzioni o qualsiasi variabile globale.
|
||||
|
||||
L'esempio precedente non aveva operazioni complicate ma il metodo `splice` ha cambiato l'array originale e ha provocato un bug.
|
||||
|
||||
Ricorda che nella programmazione funzionale, la modifica o alterazione delle cose è chiamata <dfn>mutazione</dfn>, e il risultato è chiamato <dfn>effetto collaterale</dfn>. Una funzione, idealmente, dovrebbe essere una <dfn>funzione pura</dfn>, cioè non dovrebbe provocare effetti collaterali.
|
||||
|
||||
Cerchiamo di padroneggiare questa disciplina e non modificare alcuna variabile o oggetto nel nostro codice.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Compila il codice per la funzione `incrementer` in modo che restituisca il valore della variabile globale `fixedValue` aumentata di uno.
|
||||
|
||||
# --hints--
|
||||
|
||||
La tua funzione `incrementer` non dovrebbe cambiare il valore di `fixedValue` (che è `4`).
|
||||
|
||||
```js
|
||||
incrementer();
|
||||
assert(fixedValue === 4);
|
||||
```
|
||||
|
||||
La tua funzione `incrementer` dovrebbe restituire un valore di una unità più grande del valore `fixedValue`.
|
||||
|
||||
```js
|
||||
const __newValue = incrementer();
|
||||
assert(__newValue === 5);
|
||||
```
|
||||
|
||||
La tua funzione `incrementer` dovrebbe restituire un valore basato sul valore della variabile globale `fixedValue`.
|
||||
|
||||
```js
|
||||
(function () {
|
||||
fixedValue = 10;
|
||||
const newValue = incrementer();
|
||||
assert(fixedValue === 10 && newValue === 11);
|
||||
fixedValue = 4;
|
||||
})();
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var fixedValue = 4;
|
||||
|
||||
function incrementer () {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var fixedValue = 4
|
||||
|
||||
function incrementer() {
|
||||
return fixedValue + 1
|
||||
}
|
||||
```
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6c
|
||||
title: Combinare un array in una stringa usando il metodo join
|
||||
challengeType: 1
|
||||
forumTopicId: 18221
|
||||
dashedName: combine-an-array-into-a-string-using-the-join-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Il metodo `join` viene utilizzato per unire gli elementi di un array per creare una stringa. Prende un argomento che sarà il delimitatore che viene utilizzato per separare gli elementi dell'array nella stringa.
|
||||
|
||||
Ecco un esempio:
|
||||
|
||||
```js
|
||||
var arr = ["Hello", "World"];
|
||||
var str = arr.join(" ");
|
||||
```
|
||||
|
||||
`str` conterrà la stringa `Hello World`.
|
||||
# --instructions--
|
||||
|
||||
Usa il metodo `join` (tra gli altri) all'interno della funzione `sentensify` per creare una frase a partire dalle parole contenute nella stringa `str`. La funzione dovrebbe restituire una stringa. Ad esempio, `I-like-Star-Wars` sarebbe stato convertito in `I like Star Wars`. Per questa sfida, non utilizzare il metodo `replace`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice dovrebbe utilizzare il metodo `join`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.join/g));
|
||||
```
|
||||
|
||||
Il tuo codice non dovrebbe usare il metodo `replace`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?replace/g));
|
||||
```
|
||||
|
||||
`sentensify("May-the-force-be-with-you")` dovrebbe restituire una stringa.
|
||||
|
||||
```js
|
||||
assert(typeof sentensify('May-the-force-be-with-you') === 'string');
|
||||
```
|
||||
|
||||
`sentensify("May-the-force-be-with-you")` dovrebbe restituire la stringa `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")` dovrebbe restituire la stringa `The force is strong with this one`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
sentensify('The.force.is.strong.with.this.one') ===
|
||||
'The force is strong with this one'
|
||||
);
|
||||
```
|
||||
|
||||
`sentensify("There,has,been,an,awakening")` dovrebbe restituire la stringa `There has been an awakening`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
sentensify('There,has,been,an,awakening') === 'There has been an awakening'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sentensify(str) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
sentensify("May-the-force-be-with-you");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sentensify(str) {
|
||||
// Only change code below this line
|
||||
return str.split(/\W/).join(' ');
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b66
|
||||
title: Combinare due array usando il metodo concat
|
||||
challengeType: 1
|
||||
forumTopicId: 301229
|
||||
dashedName: combine-two-arrays-using-the-concat-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Concatenazione</dfn> significa unire gli oggetti dal primo all'ultimo. JavaScript offre il metodo `concat` sia per le stringhe per gli array, e funziona allo stesso modo per entrambi. Per gli array, il metodo viene chiamato su un array, quindi viene fornito un altro array come argomento a `concat`, in modo da aggiungerlo alla fine del primo array. Questo restituisce un nuovo array e non muta nessuno degli array originali. Ecco un esempio:
|
||||
|
||||
```js
|
||||
[1, 2, 3].concat([4, 5, 6]);
|
||||
```
|
||||
|
||||
L'array restituito sarà `[1, 2, 3, 4, 5, 6]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Utilizza il metodo `concat` nella funzione `nonMutatingConcat` per concatenare `attach` alla fine di `original`. La funzione dovrebbe restituire l'array concatenato.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice dovrebbe usare il metodo `concat`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.concat/g));
|
||||
```
|
||||
|
||||
L'array `first` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
|
||||
```
|
||||
|
||||
L'array `second` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
|
||||
```
|
||||
|
||||
`nonMutatingConcat([1, 2, 3], [4, 5])` dovrebbe restituire `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(nonMutatingConcat([1, 2, 3], [4, 5])) ===
|
||||
JSON.stringify([1, 2, 3, 4, 5])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nonMutatingConcat(original, attach) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingConcat(first, second);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nonMutatingConcat(original, attach) {
|
||||
// Only change code below this line
|
||||
return original.concat(attach);
|
||||
// Only change code above this line
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingConcat(first, second);
|
||||
```
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b62
|
||||
title: Implementare map in un prototipo
|
||||
challengeType: 1
|
||||
forumTopicId: 301230
|
||||
dashedName: implement-map-on-a-prototype
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Come hai visto applicando in precedenza `Array.prototype.map()`, o semplicemente `map()`, il metodo `map` restituisce un array della stessa lunghezza di quello su cui è stato chiamato. Inoltre non altera l'array originale, purché la sua funzione di callback non lo faccia.
|
||||
|
||||
In altre parole, `map` è una funzione pura, e il suo output dipende esclusivamente dai suoi input. Inoltre, prende un'altra funzione come suo argomento.
|
||||
|
||||
Potresti imparare molto sul metodo `map` implementandone la tua versione. Ti raccomandiamo di utilizzare un ciclo `for` o `Array.prototype.forEach()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Scrivi il tuo `Array.prototype.myMap()`, che dovrebbe comportarsi esattamente come `Array.prototype.map()`. Non dovresti usare il metodo `map` integrato. L'istanza `Array` può essere consultata nel metodo `myMap` usando `this`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`new_s` dovrebbe essere uguale a `[46, 130, 196, 10]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]));
|
||||
```
|
||||
|
||||
Il tuo codice non dovrebbe usare il metodo `map`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?map/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myMap = function(callback) {
|
||||
var newArray = [];
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
var new_s = s.myMap(function(item) {
|
||||
return item * 2;
|
||||
});
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// the global Array
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myMap = function(callback) {
|
||||
var newArray = [];
|
||||
// Only change code below this line
|
||||
for (var elem of this) {
|
||||
newArray.push(callback(elem));
|
||||
}
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
var new_s = s.myMap(function(item) {
|
||||
return item * 2;
|
||||
});
|
||||
```
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b64
|
||||
title: Implementare il metodo filter in un prototipo
|
||||
challengeType: 1
|
||||
forumTopicId: 301231
|
||||
dashedName: implement-the-filter-method-on-a-prototype
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Potresti imparare molto sul metodo `filter` implementandone la tua versione. Ti raccomandiamo di utilizzare un ciclo `for` o `Array.prototype.forEach()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Scrivi il tuo `Array.prototype.myFilter()`, che dovrebbe comportarsi esattamente come `Array.prototype.filter()`. Non dovresti usare il metodo `filter` incorporato. L'istanza `Array` può essere consultata nel metodo `myFilter` usando `this`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`new_s` dovrebbe essere uguale a `[23, 65, 5]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]));
|
||||
```
|
||||
|
||||
Il tuo codice non dovrebbe usare il metodo `filter`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?filter/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myFilter = function(callback) {
|
||||
// Only change code below this line
|
||||
var newArray = [];
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
var new_s = s.myFilter(function(item) {
|
||||
return item % 2 === 1;
|
||||
});
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// the global Array
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myFilter = function(callback) {
|
||||
var newArray = [];
|
||||
// Only change code below this line
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
if (callback(this[i])) newArray.push(this[i]);
|
||||
}
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
var new_s = s.myFilter(function(item) {
|
||||
return item % 2 === 1;
|
||||
});
|
||||
```
|
@ -0,0 +1,100 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b70
|
||||
title: Introduzione al currying e all'applicazione parziale
|
||||
challengeType: 1
|
||||
forumTopicId: 301232
|
||||
dashedName: introduction-to-currying-and-partial-application
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'<dfn>arietà</dfn> di una funzione è il numero di argomenti che essa richiede. Effetturare il <dfn>curry</dfn> di una funzione significa convertire una funzione di arietà N in N funzioni di arietà 1.
|
||||
|
||||
In altre parole, questa operazione ristruttura una funzione in modo che prenda un argomento, poi restituisce un'altra funzione che prende l'argomento successivo, e così via.
|
||||
|
||||
Ecco un esempio:
|
||||
|
||||
```js
|
||||
function unCurried(x, y) {
|
||||
return x + y;
|
||||
}
|
||||
|
||||
function curried(x) {
|
||||
return function(y) {
|
||||
return x + y;
|
||||
}
|
||||
}
|
||||
|
||||
const curried = x => y => x + y
|
||||
|
||||
curried(1)(2)
|
||||
```
|
||||
|
||||
`curried(1)(2)` restituirà `3`.
|
||||
|
||||
Questo sarà utile nel tuo programma se non sarai in grado di fornire tutti gli argomenti ad una funzione in una sola volta. Potrai salvare ogni chiamata di funzione in una variabile, che manterrà il riferimento alla funzione restituita, che prenderà l'argomento successivo quando sarà disponibile. Ecco un esempio usando la funzione curried dell'esempio visto sopra:
|
||||
|
||||
```js
|
||||
var funcForY = curried(1);
|
||||
console.log(funcForY(2)); // 3
|
||||
```
|
||||
|
||||
Allo stesso modo, <dfn>l'applicazione parziale</dfn> può essere descritta come l'applicazione di alcuni argomenti a una funzione alla volta e la restituzione di un'altra funzione che viene applicata a più argomenti. Ecco un esempio:
|
||||
|
||||
```js
|
||||
function impartial(x, y, z) {
|
||||
return x + y + z;
|
||||
}
|
||||
var partialFn = impartial.bind(this, 1, 2);
|
||||
partialFn(10); // 13
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Riempi il corpo della funzione `add` in modo che usi il currying per aggiungere i parametri `x`, `y`, e `z`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`add(10)(20)(30)` dovrebbe restituire `60`.
|
||||
|
||||
```js
|
||||
assert(add(10)(20)(30) === 60);
|
||||
```
|
||||
|
||||
`add(1)(2)(3)` dovrebbe restituire `6`.
|
||||
|
||||
```js
|
||||
assert(add(1)(2)(3) === 6);
|
||||
```
|
||||
|
||||
`add(11)(22)(33)` dovrebbe restituire `66`.
|
||||
|
||||
```js
|
||||
assert(add(11)(22)(33) === 66);
|
||||
```
|
||||
|
||||
Il tuo codice dovrebbe includere una dichiarazione finale che restituisca `x + y + z`.
|
||||
|
||||
```js
|
||||
assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function add(x) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
add(10)(20)(30);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const add = x => y => z => x + y + z
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 587d7b8d367417b2b2512b5b
|
||||
title: Scoprire la programmazione funzionale
|
||||
challengeType: 1
|
||||
forumTopicId: 301233
|
||||
dashedName: learn-about-functional-programming
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
La programmazione funzionale è uno stile di programmazione in cui le soluzioni sono funzioni semplici e isolate, senza effetti indesiderati al di fuori del campo di applicazione della funzione: `INPUT -> PROCESS -> OUTPUT`
|
||||
|
||||
La programmazione funzionale riguarda:
|
||||
|
||||
1) Funzioni isolate - non c'è dipendenza dallo stato del programma, che include variabili globali che sono soggette a cambiamenti
|
||||
|
||||
2) Funzioni pure - lo stesso input dà sempre lo stesso output
|
||||
|
||||
3) Funzioni con effetti collaterali limitati - eventuali cambiamenti, o mutazioni, allo stato del programma al di fuori della funzione sono attentamente controllati
|
||||
|
||||
# --instructions--
|
||||
|
||||
I membri di freeCodeCamp amano il tè.
|
||||
|
||||
Nell'editor di codice, le funzioni `prepareTea` e `getTea` sono già definite per te. Chiama la funzione `getTea` per ottenere 40 tazze di tè per la squadra, e memorizzale nella variabile `tea4TeamFCC`.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `tea4TeamFCC` dovrebbe contenere 40 tazze di tè per la squadra.
|
||||
|
||||
```js
|
||||
assert(tea4TeamFCC.length === 40);
|
||||
```
|
||||
|
||||
La variabile `tea4TeamFCC` dovrebbe contenere tazze di tè verde.
|
||||
|
||||
```js
|
||||
assert(tea4TeamFCC[0] === 'greenTea');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Function that returns a string representing a cup of green tea
|
||||
const prepareTea = () => 'greenTea';
|
||||
|
||||
/*
|
||||
Given a function (representing the tea type) and number of cups needed, the
|
||||
following function returns an array of strings (each representing a cup of
|
||||
a specific type of tea).
|
||||
*/
|
||||
const getTea = (numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
const tea4TeamFCC = null;
|
||||
// Only change code above this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const prepareTea = () => 'greenTea';
|
||||
|
||||
const getTea = (numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
const tea4TeamFCC = getTea(40);
|
||||
```
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5f
|
||||
title: Passare gli argomenti per evitare la dipendenza esterna in una funzione
|
||||
challengeType: 1
|
||||
forumTopicId: 301234
|
||||
dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
L'ultima sfida è stata un passo più vicino ai principi della programmazione funzionale, ma manca ancora qualcosa.
|
||||
|
||||
Non abbiamo modificato il valore globale della variabile, ma la funzione `incrementer` non avrebbe funzionato senza che la variabile globale `fixedValue` fosse lì.
|
||||
|
||||
Un altro principio della programmazione funzionale è quello di dichiarare sempre esplicitamente le dipendenze. Questo significa che se una funzione dipende dalla presenza di una variabile o di un oggetto, devi passare quella variabile o l'oggetto direttamente nella funzione come argomento.
|
||||
|
||||
Da questo principio derivano diverse buone conseguenze. La funzione è più facile da testare, si sa esattamente che input prende, e non dipenderà da nient'altro nel tuo programma.
|
||||
|
||||
Questo può darti più fiducia quando alteri, rimuovi o aggiungi del codice. Saprai cosa puoi o non puoi cambiare e potrai vedere dove sono le potenziali trappole.
|
||||
|
||||
Infine, la funzione produrrà sempre lo stesso output per lo stesso insieme di input, indipendentemente da quale parte del codice lo esegue.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Aggiorniamo la funzione `incrementer` per dichiarare chiaramente le sue dipendenze.
|
||||
|
||||
Scrivi la funzione `incrementer` in modo che richieda un argomento, quindi restituisca un risultato dopo aver aumentato il valore di uno.
|
||||
|
||||
# --hints--
|
||||
|
||||
La tua funzione `incrementer` non dovrebbe cambiare il valore di `fixedValue` (che è `4`).
|
||||
|
||||
```js
|
||||
assert(fixedValue === 4);
|
||||
```
|
||||
|
||||
La tua funzione `incrementer` dovrebbe prendere un argomento.
|
||||
|
||||
```js
|
||||
assert(incrementer.length === 1);
|
||||
```
|
||||
|
||||
La tua funzione `incrementer` dovrebbe restituire il valore di `fixedValue` aumentato di una unità.
|
||||
|
||||
```js
|
||||
const __newValue = incrementer(fixedValue);
|
||||
assert(__newValue === 5);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var fixedValue = 4;
|
||||
|
||||
// Only change code below this line
|
||||
function incrementer () {
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var fixedValue = 4;
|
||||
|
||||
// Only change code below this line
|
||||
function incrementer (fixedValue) {
|
||||
return fixedValue + 1;
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
|
||||
```
|
@ -0,0 +1,141 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b60
|
||||
title: Refactoring delle variabili globali fuori dalle funzioni
|
||||
challengeType: 1
|
||||
forumTopicId: 301235
|
||||
dashedName: refactor-global-variables-out-of-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Finora abbiamo visto due principi distinti per la programmazione funzionale:
|
||||
|
||||
1) Non modificare una variabile o un oggetto - se necessario creare nuove variabili e oggetti e restituirli da una funzione. Suggerimento: usando qualcosa come `var newArr = arrVar`, dove `arrVar` è un array, creerai semplicemente un riferimento alla variabile esistente e non una copia. Quindi cambiando un valore in `newArr` cambierà anche il valore in `arrVar`.
|
||||
|
||||
2) Dichiarare i parametri della funzione - qualsiasi calcolo all'interno di una funzione deve dipendere solo dagli argomenti passati alla funzione, e non da qualsiasi oggetto o variabile globale.
|
||||
|
||||
Aggiungere uno a un certo numero non è molto eccitante, ma potremo applicare questi stessi principi quando lavoreremo con array o oggetti più complessi.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Riscrivi il codice in modo che l'array globale `bookList` non venga modificato all'interno di nessuna funzione. La funzione `add` dovrebbe aggiungere il `bookName` dato alla fine dell'array passato e restituire un nuovo array (lista). La funzione `remove` dovrebbe rimuovere il `bookName` dato dall'array che le viene passato.
|
||||
|
||||
**Nota:** Entrambe le funzioni dovrebbero restituire un array, e tutti i nuovi parametri dovrebbero essere aggiunti prima del parametro `bookName`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`bookList` non dovrebbe cambiare e dovrebbe rimanere uguale a `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(bookList) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'On The Electrodynamics of Moving Bodies',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
`newBookList` dovrebbe essere uguale 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(
|
||||
JSON.stringify(newBookList) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'On The Electrodynamics of Moving Bodies',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae',
|
||||
'A Brief History of Time'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
`newerBookList` dovrebbe essere uguale a `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(newerBookList) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
`newestBookList` dovrebbe essere uguale a `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(newestBookList) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae',
|
||||
'A Brief History of Time'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
// Change code below this line
|
||||
function add (bookName) {
|
||||
|
||||
bookList.push(bookName);
|
||||
return bookList;
|
||||
|
||||
// Change code above this line
|
||||
}
|
||||
|
||||
// Change code below this line
|
||||
function remove (bookName) {
|
||||
var book_index = bookList.indexOf(bookName);
|
||||
if (book_index >= 0) {
|
||||
|
||||
bookList.splice(book_index, 1);
|
||||
return bookList;
|
||||
|
||||
// Change code above this line
|
||||
}
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
|
||||
console.log(bookList);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
function add (bookList, bookName) {
|
||||
return [...bookList, bookName];
|
||||
}
|
||||
|
||||
function remove (bookList, bookName) {
|
||||
const bookListCopy = [...bookList];
|
||||
const bookNameIndex = bookList.indexOf(bookName);
|
||||
if (bookNameIndex >= 0) {
|
||||
bookListCopy.splice(bookNameIndex, 1);
|
||||
}
|
||||
return bookListCopy;
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 9d7123c8c441eeafaeb5bdef
|
||||
title: Rimuovere gli elementi da un array usando slice invece di splice
|
||||
challengeType: 1
|
||||
forumTopicId: 301236
|
||||
dashedName: remove-elements-from-an-array-using-slice-instead-of-splice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un'operazione che si fa comunemente lavorando con gli array è quella di rimuovere degli elemento mantenendo il resto dell'array. A questo scopo JavaScript offre il metodo `splice`, che richiede degli argomenti per la posizione (indice) di dove iniziare a rimuovere gli elementi, e per il numero di elementi da rimuovere. Se il secondo argomento non è fornito, il comportamento predefinito è quello di rimuovere gli elementi fino alla fine. Tuttavia, il metodo `splice` muta l'array originale su cui viene chiamato. Ecco un esempio:
|
||||
|
||||
```js
|
||||
var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
cities.splice(3, 1);
|
||||
```
|
||||
|
||||
Qui `splice` restituisce la stringa `London` e la elimina dall'array delle città. `cities` avrà il valore `["Chicago", "Delhi", "Islamabad", "Berlin"]`.
|
||||
|
||||
Come abbiamo visto nell'ultima sfida, il metodo `slice` non muta l'array originale, ma ne restituisce uno nuovo che può essere salvato in una variabile. Ricorda che il metodo `slice` richiede due argomenti per gli indici di inizio e fine (non inclusiva) della "fetta" (slice), e restituisce quegli elementi in un nuovo array. Usando il metodo `slice` invece di `splice` si evita qualsiasi effetto collaterale di mutazione dell'array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Riscrivi la funzione `nonMutatingSplice` usando `slice` invece di `splice`. Questo dovrebbe limitare l'array `cities` fornito a una lunghezza di 3, e restituire un nuovo array contenente solo i primi tre elementi.
|
||||
|
||||
Non mutare l'array originale fornito alla funzione.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice dovrebbe utilizzare il metodo `slice`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.slice/g));
|
||||
```
|
||||
|
||||
Il tuo codice non dovrebbe usare il metodo `splice`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?splice/g));
|
||||
```
|
||||
|
||||
L'array `inputCities` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(inputCities) ===
|
||||
JSON.stringify(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
|
||||
);
|
||||
```
|
||||
|
||||
`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` dovrebbe restituire `["Chicago", "Delhi", "Islamabad"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(
|
||||
nonMutatingSplice(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
|
||||
) === JSON.stringify(['Chicago', 'Delhi', 'Islamabad'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nonMutatingSplice(cities) {
|
||||
// Only change code below this line
|
||||
return cities.splice(3);
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
nonMutatingSplice(inputCities);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nonMutatingSplice(cities) {
|
||||
// Only change code below this line
|
||||
return cities.slice(0,3);
|
||||
// Only change code above this line
|
||||
}
|
||||
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
nonMutatingSplice(inputCities);
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b6a
|
||||
title: Restituire un array ordinato senza cambiare l'array originale
|
||||
challengeType: 1
|
||||
forumTopicId: 301237
|
||||
dashedName: return-a-sorted-array-without-changing-the-original-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un effetto collaterale del metodo `sort` è che cambia l'ordine degli elementi nell'array originale. In altre parole, muta l'array "in place" (in posizione). Un modo per evitarlo è quello di concatenare un array vuoto a quello che deve essere ordinato (ricorda che `slice` e `concat` restituiscono un nuovo array), per poi eseguire il metodo `sort`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa il metodo `sort` nella funzione `nonMutatingSort` per ordinare gli elementi di un array in ordine crescente. La funzione dovrebbe restituire un nuovo array, e non mutare la variabile `globalArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice dovrebbe usare il metodo `sort`.
|
||||
|
||||
```js
|
||||
assert(nonMutatingSort.toString().match(/\.sort/g));
|
||||
```
|
||||
|
||||
La variabile `globalArray` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
|
||||
```
|
||||
|
||||
`nonMutatingSort(globalArray)` dovrebbe restituire `[2, 3, 5, 6, 9]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(nonMutatingSort(globalArray)) ===
|
||||
JSON.stringify([2, 3, 5, 6, 9])
|
||||
);
|
||||
```
|
||||
|
||||
`nonMutatingSort(globalArray)` non dovrebbe essere "hard coded" (cioè codificato esplicitamente nel codice).
|
||||
|
||||
```js
|
||||
assert(!nonMutatingSort.toString().match(/[23569]/g));
|
||||
```
|
||||
|
||||
La funzione dovrebbe restituire un nuovo array, non l'array originale che le viene passato.
|
||||
|
||||
```js
|
||||
assert(nonMutatingSort(globalArray) !== globalArray);
|
||||
```
|
||||
|
||||
`nonMutatingSort([1, 30, 4, 21, 100000])` dovrebbe restituire `[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])` dovrebbe restituire `[99, 104, 140000]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(nonMutatingSort([140000, 104, 99])) ===
|
||||
JSON.stringify([99, 104, 140000]))
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var globalArray = [5, 6, 3, 2, 9];
|
||||
function nonMutatingSort(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
nonMutatingSort(globalArray);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var globalArray = [5, 6, 3, 2, 9];
|
||||
function nonMutatingSort(arr) {
|
||||
// Only change code below this line
|
||||
return [].concat(arr).sort((a,b) => a-b);
|
||||
// Only change code above this line
|
||||
}
|
||||
nonMutatingSort(globalArray);
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 587d7b90367417b2b2512b65
|
||||
title: Restituire parte di un array utilizzando il metodo slice
|
||||
challengeType: 1
|
||||
forumTopicId: 301239
|
||||
dashedName: return-part-of-an-array-using-the-slice-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Il metodo `slice` restituisce una copia di alcuni elementi di un array. Può prendere due argomenti, il primo è l'indice di dove iniziare la "slice" (fetta), il secondo è l'indice di dove finirla (ed è non-inclusivo, cioè non è incluso nella fetta). Se gli argomenti non sono forniti, il comportamento predefinito è quello di iniziare all'inizio dell'array e di andare fino alla fine, che è un modo semplice per fare una copia dell'intero array. Il metodo `slice` non muta l'array originale, ma ne restituisce uno nuovo.
|
||||
|
||||
Ecco un esempio:
|
||||
|
||||
```js
|
||||
var arr = ["Cat", "Dog", "Tiger", "Zebra"];
|
||||
var newArray = arr.slice(1, 3);
|
||||
```
|
||||
|
||||
`newArray` avrà il valore `["Dog", "Tiger"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa il metodo `slice` nella funzione `sliceArray` per restituire parte dell'array `anim`, dati gli indici `beginSlice` e `endSlice`. La funzione dovrebbe restituire un array.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice dovrebbe utilizzare il metodo `slice`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.slice/g));
|
||||
```
|
||||
|
||||
La variabile `inputAnim` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(inputAnim) ===
|
||||
JSON.stringify(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'])
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` dovrebbe restituire `["Dog", "Tiger"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 3)) ===
|
||||
JSON.stringify(['Dog', 'Tiger'])
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` dovrebbe restituire `["Cat"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 0, 1)) ===
|
||||
JSON.stringify(['Cat'])
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` dovrebbe restituire `["Dog", "Tiger", "Zebra"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 4)) ===
|
||||
JSON.stringify(['Dog', 'Tiger', 'Zebra'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sliceArray(anim, beginSlice, endSlice) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
|
||||
sliceArray(inputAnim, 1, 3);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sliceArray(anim, beginSlice, endSlice) {
|
||||
// Only change code below this line
|
||||
return anim.slice(beginSlice, endSlice)
|
||||
// Only change code above this line
|
||||
}
|
||||
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
|
||||
sliceArray(inputAnim, 1, 3);
|
||||
```
|
@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b69
|
||||
title: Ordinare un array alfabeticamente usando il metodo sort
|
||||
challengeType: 1
|
||||
forumTopicId: 18303
|
||||
dashedName: sort-an-array-alphabetically-using-the-sort-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Il metodo `sort` ordina gli elementi di un array in base alla funzione "callback" (una funzione, passata come argomento, che dovrà essere usata dal metodo per eseguire l'ordinamento).
|
||||
|
||||
Ad esempio:
|
||||
|
||||
```js
|
||||
function ascendingOrder(arr) {
|
||||
return arr.sort(function(a, b) {
|
||||
return a - b;
|
||||
});
|
||||
}
|
||||
ascendingOrder([1, 5, 2, 3, 4]);
|
||||
```
|
||||
|
||||
Questo restituirà il valore `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
function reverseAlpha(arr) {
|
||||
return arr.sort(function(a, b) {
|
||||
return a === b ? 0 : a < b ? 1 : -1;
|
||||
});
|
||||
}
|
||||
reverseAlpha(['l', 'h', 'z', 'b', 's']);
|
||||
```
|
||||
|
||||
Questo restituirà il valore `['z', 's', 'l', 'h', 'b']`.
|
||||
|
||||
Il metodo di ordinamento predefinito di JavaScript è in base ai valori Unicode della stringa, e questo può dare risultati inattesi. Pertanto, è consigliabile fornire una funzione di callback per specificare come ordinare gli elementi dell'array. Quando viene fornita una tale funzione di callback, chiamata normalmente `compareFunction`, gli elementi dell'array sono ordinati in base al valore di ritorno della `compareFunction`: se `compareFunction(a,b)` restituisce un valore inferiore a 0 per due elementi `a` e `b`, allora `a` verrà prima di `b` nell'ordinamento. Se `compareFunction(a,b)` restituisce un valore maggiore di 0 per due elementi `a` e `b`, allora `b` verrà prima di `a`. Se `compareFunction(a,b)` restituisce un valore pari a 0 per due elementi `a` e `b`, allora `a` e `b` rimarranno invariati.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa il metodo `sort` nella funzione `alphabeticalOrder` per ordinare gli elementi di `arr` in ordine alfabetico.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice dovrebbe usare il metodo `sort`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.sort/g));
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` dovrebbe restituire `["a", "a", "c", "d", "g", "z"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(alphabeticalOrder(['a', 'd', 'c', 'a', 'z', 'g'])) ===
|
||||
JSON.stringify(['a', 'a', 'c', 'd', 'g', 'z'])
|
||||
);
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` dovrebbe restituire `["a", "h", "m", "m", "n", "x"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(alphabeticalOrder(['x', 'h', 'a', 'm', 'n', 'm'])) ===
|
||||
JSON.stringify(['a', 'h', 'm', 'm', 'n', 'x'])
|
||||
);
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` dovrebbe restituire `["a", "a", "a", "a", "t", "x"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(alphabeticalOrder(['a', 'a', 'a', 'a', 'x', 't'])) ===
|
||||
JSON.stringify(['a', 'a', 'a', 'a', 't', 'x'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function alphabeticalOrder(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function alphabeticalOrder(arr) {
|
||||
// Only change code below this line
|
||||
return arr.sort();
|
||||
// Only change code above this line
|
||||
}
|
||||
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
|
||||
```
|
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6b
|
||||
title: Suddividere una stringa in un array usando il metodo split
|
||||
challengeType: 1
|
||||
forumTopicId: 18305
|
||||
dashedName: split-a-string-into-an-array-using-the-split-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Il metodo `split` divide una stringa in un array di stringhe. Esso richiede un argomento per il delimitatore, che può essere un carattere da usare per spezzare la stringa o un'espressione regolare. Ad esempio, se il delimitatore è uno spazio, si ottiene una serie di parole, e se il delimitatore è una stringa vuota, si ottiene un array di ogni carattere nella stringa.
|
||||
|
||||
Ecco un esempio che divide una stringa in base agli spazi, poi un altro in base alle cifre facendo uso di un'espressione regolare:
|
||||
|
||||
```js
|
||||
var str = "Hello World";
|
||||
var bySpace = str.split(" ");
|
||||
|
||||
var otherString = "How9are7you2today";
|
||||
var byDigits = otherString.split(/\d/);
|
||||
```
|
||||
|
||||
`bySpace` avrà il valore `["Hello", "World"]` e `byDigits` avrà il valore `["How", "are", "you", "today"]`.
|
||||
|
||||
Dal momento che le stringhe sono immutabili, il metodo `split` rende più facile lavorare con esse.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa il metodo `split` all'interno della funzione `splitify` per dividere `str` in un array di parole. La funzione dovrebbe restituire l'array. Nota che le parole non sono sempre separate da spazi, e l'array non dovrebbe contenere punteggiatura.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice dovrebbe utilizzare il metodo `split`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.split/g));
|
||||
```
|
||||
|
||||
`splitify("Hello World,I-am code")` dovrebbe restituire `["Hello", "World", "I", "am", "code"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(splitify('Hello World,I-am code')) ===
|
||||
JSON.stringify(['Hello', 'World', 'I', 'am', 'code'])
|
||||
);
|
||||
```
|
||||
|
||||
`splitify("Earth-is-our home")` dovrebbe restituire `["Earth", "is", "our", "home"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(splitify('Earth-is-our home')) ===
|
||||
JSON.stringify(['Earth', 'is', 'our', 'home'])
|
||||
);
|
||||
```
|
||||
|
||||
`splitify("This.is.a-sentence")` dovrebbe restituire `["This", "is", "a", "sentence"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(splitify('This.is.a-sentence')) ===
|
||||
JSON.stringify(['This', 'is', 'a', 'sentence'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function splitify(str) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
splitify("Hello World,I-am code");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function splitify(str) {
|
||||
// Only change code below this line
|
||||
return str.split(/\W/);
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
@ -0,0 +1,112 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5c
|
||||
title: Comprendere la terminologia della programmazione funzionale
|
||||
challengeType: 1
|
||||
forumTopicId: 301240
|
||||
dashedName: understand-functional-programming-terminology
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
La squadra di FCC ha avuto uno sbalzo di umore e ora vuole due tipi di tè: tè verde e tè nero. Fatto generale: gli sbalzi di umore dei clienti sono piuttosto comuni.
|
||||
|
||||
Con queste informazioni, avremo bisogno di rivedere la funzione `getTea` dall'ultima sfida per gestire varie richieste di tè. Possiamo modificare `getTea` in modo che accetti una funzione come parametro per poter cambiare il tipo di tè che prepara. Questo rende `getTea` più flessibile e dà al programmatore più controllo quando le richieste del cliente cambiano.
|
||||
|
||||
Prima però, vediamo un po' di terminologia funzionale:
|
||||
|
||||
<dfn>Callback</dfn> sono le funzioni che vengono passate a un'altra funzione per decidere l'invocazione di quella funzione. Potresti averle viste passare ad altri metodi, ad esempio in `filter`, la funzione callback dice a JavaScript i criteri per filtrare un array.
|
||||
|
||||
Funzioni che possono essere assegnate a una variabile, passate a un'altra funzione, o restituite da un'altra funzione proprio come qualsiasi altro valore normale, sono chiamate <dfn>funzioni di prima classe</dfn>. In JavaScript, tutte le funzioni sono di prima classe.
|
||||
|
||||
Le funzioni che prendono una funzione come argomento, o restituiscono una funzione come valore di ritorno sono chiamate funzioni <dfn>di ordine superiore</dfn>.
|
||||
|
||||
Quando le funzioni sono passate o restituite da un'altra funzione, le funzioni che sono state passate o restituite possono essere chiamate un <dfn>lambda</dfn>.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Prepara 27 tazze di tè verde e 13 tazze di tè nero e conservale rispettivamente nelle variabili `tea4GreenTeamFCC` e `tea4BlackTeamFCC`. Nota che la funzione `getTea` è stata modificata e ora prende una funzione come primo argomento.
|
||||
|
||||
Nota: I dati (il numero di tazze di tè) sono forniti come ultimo argomento. Ne discuteremo di più nelle lezioni successive.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `tea4GreenTeamFCC` dovrebbe contenere 27 tazze di tè verde per la squadra.
|
||||
|
||||
```js
|
||||
assert(tea4GreenTeamFCC.length === 27);
|
||||
```
|
||||
|
||||
La variabile `tea4GreenTeamFCC` dovrebbe contenere tazze di tè verde.
|
||||
|
||||
```js
|
||||
assert(tea4GreenTeamFCC[0] === 'greenTea');
|
||||
```
|
||||
|
||||
La variabile `tea4BlackTeamFCC` dovrebbe contenere 13 tazze di tè nero.
|
||||
|
||||
```js
|
||||
assert(tea4BlackTeamFCC.length === 13);
|
||||
```
|
||||
|
||||
La variabile `tea4BlackTeamFCC` dovrebbe contenere tazze di tè nero.
|
||||
|
||||
```js
|
||||
assert(tea4BlackTeamFCC[0] === 'blackTea');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Function that returns a string representing a cup of green tea
|
||||
const prepareGreenTea = () => 'greenTea';
|
||||
|
||||
// Function that returns a string representing a cup of black tea
|
||||
const prepareBlackTea = () => 'blackTea';
|
||||
|
||||
/*
|
||||
Given a function (representing the tea type) and number of cups needed, the
|
||||
following function returns an array of strings (each representing a cup of
|
||||
a specific type of tea).
|
||||
*/
|
||||
const getTea = (prepareTea, numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
const tea4GreenTeamFCC = null;
|
||||
const tea4BlackTeamFCC = null;
|
||||
// Only change code above this line
|
||||
|
||||
console.log(
|
||||
tea4GreenTeamFCC,
|
||||
tea4BlackTeamFCC
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const prepareGreenTea = () => 'greenTea';
|
||||
const prepareBlackTea = () => 'blackTea';
|
||||
|
||||
const getTea = (prepareTea, numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
const tea4BlackTeamFCC = getTea(prepareBlackTea, 13);
|
||||
const tea4GreenTeamFCC = getTea(prepareGreenTea, 27);
|
||||
```
|
@ -0,0 +1,145 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5d
|
||||
title: Comprendere i pericoli dell'utilizzo del codice imperativo
|
||||
challengeType: 1
|
||||
forumTopicId: 301241
|
||||
dashedName: understand-the-hazards-of-using-imperative-code
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
La programmazione funzionale è una buona abitudine. Mantiene il tuo codice facile da gestire e ti salva da bug subdoli. Prima di arrivarci, diamo un'occhiata a un approccio imperativo alla programmazione per evidenziare dove si possono presentare i problemi.
|
||||
|
||||
In inglese (e in molte altre lingue), il tempo imperativo viene usato per dare ordini. Allo stesso modo, uno stile imperativo nella programmazione è quello che dà al computer una serie di istruzioni per eseguire un compito.
|
||||
|
||||
Spesso le istruzioni cambiano lo stato del programma, ad esempio aggiornando delle variabili globali. Un classico esempio è la scrittura di un ciclo `for` che dà direttive esatte su come iterare tra gli indici di un array.
|
||||
|
||||
Al contrario, la programmazione funzionale è una forma di programmazione dichiarativa. Dici al computer cosa vuoi fare chiamando un metodo o una funzione.
|
||||
|
||||
JavaScript offre molti metodi predefiniti che gestiscono le attività comuni in modo da non dover scrivere come il computer dovrebbe eseguirle. Ad esempio, invece di usare il ciclo `for` menzionato sopra, potresti chiamare il metodo `map` che gestisce i dettagli di iterazione su un array. Questo aiuta ad evitare errori semantici, come gli errori "Fuori di uno" che sono stati coperti nella sezione Debugging.
|
||||
|
||||
Considera lo scenario: stai navigando sul web nel tuo browser e vuoi tracciare le schede che hai aperto. Cerchiamo di modellare questo usando un semplice codice orientato agli oggetti.
|
||||
|
||||
Un oggetto Window (finestra) è composto da schede, e di solito hai più di una finestra aperta. I titoli di ogni sito aperto in ogni oggetto Window sono memorizzati in un array. Dopo aver lavorato nel browser (apertura di nuove schede, fusione di finestre e chiusura di schede), desideri visualizzare nella console le schede rimaste aperte. Le schede chiuse vengono rimosse dall'array e le nuove schede vengono aggiunte alla fine (per semplicità).
|
||||
|
||||
L'editor di codice mostra un'implementazione di questa funzionalità con funzioni per `tabOpen()`, `tabClose()`e `join()`. L'array `tabs` è parte dell'oggetto Window che memorizza il nome delle pagine aperte.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Esamina il codice nell'editor. Viene usato un metodo che ha effetti collaterali sul programma, causando un comportamento scorretto. L'elenco finale delle schede aperte, memorizzato in `finalTabs.tabs`, dovrebbe essere `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` ma la lista prodotta dal codice è leggermente differente.
|
||||
|
||||
Cambia `Window.prototype.tabClose` in modo che rimuova la scheda corretta.
|
||||
|
||||
# --hints--
|
||||
|
||||
`finalTabs.tabs` dovrebbe essere `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
|
||||
|
||||
```js
|
||||
assert.deepEqual(finalTabs.tabs, [
|
||||
'FB',
|
||||
'Gitter',
|
||||
'Reddit',
|
||||
'Twitter',
|
||||
'Medium',
|
||||
'new tab',
|
||||
'Netflix',
|
||||
'YouTube',
|
||||
'Vine',
|
||||
'GMail',
|
||||
'Work mail',
|
||||
'Docs',
|
||||
'freeCodeCamp',
|
||||
'new tab'
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// tabs is an array of titles of each site open within the window
|
||||
var Window = function(tabs) {
|
||||
this.tabs = tabs; // We keep a record of the array inside the object
|
||||
};
|
||||
|
||||
// When you join two windows into one window
|
||||
Window.prototype.join = function (otherWindow) {
|
||||
this.tabs = this.tabs.concat(otherWindow.tabs);
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you open a new tab at the end
|
||||
Window.prototype.tabOpen = function (tab) {
|
||||
this.tabs.push('new tab'); // Let's open a new tab for now
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you close a tab
|
||||
Window.prototype.tabClose = function (index) {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var tabsBeforeIndex = this.tabs.splice(0, index); // Get the tabs before the tab
|
||||
var tabsAfterIndex = this.tabs.splice(index + 1); // Get the tabs after the tab
|
||||
|
||||
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // Join them together
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Let's create three browser windows
|
||||
var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
|
||||
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
|
||||
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
|
||||
|
||||
// Now perform the tab opening, closing, and other operations
|
||||
var finalTabs = socialWindow
|
||||
.tabOpen() // Open a new tab for cat memes
|
||||
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
|
||||
.join(workWindow.tabClose(1).tabOpen());
|
||||
console.log(finalTabs.tabs);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// tabs is an array of titles of each site open within the window
|
||||
var Window = function(tabs) {
|
||||
this.tabs = tabs; // We keep a record of the array inside the object
|
||||
};
|
||||
|
||||
// When you join two windows into one window
|
||||
Window.prototype.join = function (otherWindow) {
|
||||
this.tabs = this.tabs.concat(otherWindow.tabs);
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you open a new tab at the end
|
||||
Window.prototype.tabOpen = function (tab) {
|
||||
this.tabs.push('new tab'); // Let's open a new tab for now
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you close a tab
|
||||
Window.prototype.tabClose = function (index) {
|
||||
var tabsBeforeIndex = this.tabs.slice(0, index); // Get the tabs before the tab
|
||||
var tabsAfterIndex = this.tabs.slice(index + 1); // Get the tabs after the tab
|
||||
|
||||
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // Join them together
|
||||
return this;
|
||||
};
|
||||
|
||||
// Let's create three browser windows
|
||||
var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
|
||||
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
|
||||
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
|
||||
|
||||
// Now perform the tab opening, closing, and other operations
|
||||
var finalTabs = socialWindow
|
||||
.tabOpen() // Open a new tab for cat memes
|
||||
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
|
||||
.join(workWindow.tabClose(1).tabOpen());
|
||||
```
|
@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 587d7b88367417b2b2512b45
|
||||
title: 'Usare le funzioni di ordine superiore map, filter o reduce per risolvere un problema complesso'
|
||||
challengeType: 1
|
||||
forumTopicId: 301311
|
||||
dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Ora che hai lavorato con alcune sfide usando funzioni di ordine superiore come `map()`, `filter()`e `reduce()`, puoi applicarle per risolvere una sfida più complessa.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Completa il codice per la funzione `squareList` utilizzando qualsiasi combinazione di `map()`, `filter()`, e `reduce()`. La funzione dovrebbe restituire un nuovo array contenente i quadrati dei *soli* interi positivi (i numeri decimali non sono interi) quando viene passato un array di numeri reali. Un esempio di una serie di numeri reali è `[-3, 4.8, 5, 3, -3.2]`.
|
||||
|
||||
**Nota:** La tua funzione non dovrebbe utilizzare alcun tipo di ciclo `for` o `while` o la funzione `forEach()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`squareList` dovrebbe essere una `function`.
|
||||
|
||||
```js
|
||||
assert.typeOf(squareList, 'function'),
|
||||
'<code>squareList</code> should be a <code>function</code>';
|
||||
```
|
||||
|
||||
`for`, `while`, e `forEach` non dovrebbero essere usati.
|
||||
|
||||
```js
|
||||
assert(!code.match(/for|while|forEach/g));
|
||||
```
|
||||
|
||||
Dovrebbero essere usati `map`, `filter` o `reduce`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
__helpers
|
||||
.removeWhiteSpace(code)
|
||||
.match(/\.(map|filter|reduce)\(/g)
|
||||
);
|
||||
```
|
||||
|
||||
La funzione dovrebbe restituire un `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])` dovrebbe restituire `[16, 1764, 36]`.
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
|
||||
16,
|
||||
1764,
|
||||
36
|
||||
]);
|
||||
```
|
||||
|
||||
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` dovrebbe restituire `[9, 100, 49]`.
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [
|
||||
9,
|
||||
100,
|
||||
49
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
const squareList = arr => {
|
||||
// Only change code below this line
|
||||
return arr;
|
||||
// Only change code above this line
|
||||
};
|
||||
|
||||
const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
|
||||
console.log(squaredIntegers);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const squareList = arr => {
|
||||
const positiveIntegers = arr.filter(num => {
|
||||
return num >= 0 && Number.isInteger(num);
|
||||
});
|
||||
const squaredIntegers = positiveIntegers.map(num => {
|
||||
return num ** 2;
|
||||
});
|
||||
return squaredIntegers;
|
||||
};
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6e
|
||||
title: Usare il metodo every per controllare che ogni elemento in un array corrisponda a un criterio
|
||||
challengeType: 1
|
||||
forumTopicId: 301312
|
||||
dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Il metodo `every` funziona con gli array per controllare se *ogni* elemento supera un test particolare. Restituisce un valore booleano: `true` se tutti i valori soddisfano i criteri, `false` in caso contrario.
|
||||
|
||||
Ad esempio, il seguente codice controllerà se ogni elemento nell'array `numbers` è inferiore a 10:
|
||||
|
||||
```js
|
||||
var numbers = [1, 5, 8, 0, 10, 11];
|
||||
numbers.every(function(currentValue) {
|
||||
return currentValue < 10;
|
||||
});
|
||||
```
|
||||
|
||||
In questo caso il metodo `every` restituirà `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa il metodo `every` all'interno della funzione `checkPositive` per verificare se ogni elemento in `arr` è positivo. La funzione dovrebbe restituire un valore booleano.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice dovrebbe utilizzare il metodo `every`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.every/g));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, -4, 5])` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, 4, 5])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, -2, 3, -4, 5])` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(checkPositive([1, -2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
return arr.every(num => num > 0);
|
||||
// Only change code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
@ -0,0 +1,317 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b63
|
||||
title: Usare il metodo filter per estrarre i dati da un array
|
||||
challengeType: 1
|
||||
forumTopicId: 18179
|
||||
dashedName: use-the-filter-method-to-extract-data-from-an-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Un'altra funzione utile con gli array è `Array.prototype.filter()`, o semplicemente `filter()`.
|
||||
|
||||
`filter` chiama una funzione su ogni elemento di un array e restituisce un nuovo array contenente solo gli elementi per i quali questa funzione restituisce `true`. In altre parole, filtra l'array, sulla base della funzione passata ad esso. Come `map`, lo fa senza dover modificare l'array originale.
|
||||
|
||||
La funzione callback accetta tre argomenti. Il primo argomento è l'elemento che è correntemente in fase di elaborazione. Il secondo è l'indice di quell'elemento e il terzo è l'array su cui è stato chiamato il metodo `filter`.
|
||||
|
||||
Qui sotto trovi un esempio che utilizza il metodo `filter` sull'array `users` per restituire un nuovo array contenente solo gli utenti al di sotto dei 30 anni. Per semplicità, l'esempio utilizza solo il primo argomento della callback.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const usersUnder30 = users.filter(user => user.age < 30);
|
||||
console.log(usersUnder30);
|
||||
```
|
||||
|
||||
La console visualizzerà il valore `[ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
La variabile `watchList` contiene una serie di oggetti con informazioni su diversi film. Usa una combinazione di `filter` e `map` su `watchList` per assegnare un nuovo array di oggetti con le sole chiavi `title` e `rating`. Il nuovo array dovrebbe includere solo oggetti per i quali `imdbRating` è maggiore o uguale a 8.0. Nota che i valori di `rating` vengono salvati come stringhe nell'oggetto e potrebbe essere necessario convertirli in numeri per eseguire operazioni matematiche su di essi.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `watchList` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(
|
||||
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
|
||||
);
|
||||
```
|
||||
|
||||
Il tuo codice dovrebbe utilizzare il metodo `filter`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\s*\.\s*filter/g));
|
||||
```
|
||||
|
||||
Il tuo codice non dovrebbe utilizzare un ciclo `for`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
|
||||
```
|
||||
|
||||
`filteredList` dovrebbe essere uguale 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, [
|
||||
{ title: 'Inception', rating: '8.8' },
|
||||
{ title: 'Interstellar', rating: '8.6' },
|
||||
{ title: 'The Dark Knight', rating: '9.0' },
|
||||
{ title: 'Batman Begins', rating: '8.3' }
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// 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, Elliot 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"
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var filteredList;
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(filteredList);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// 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, Elliot 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"
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
let filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
|
||||
// Only change code above this line
|
||||
```
|
@ -0,0 +1,330 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b61
|
||||
title: Usare il metodo map per estrarre i dati da un array
|
||||
challengeType: 1
|
||||
forumTopicId: 18214
|
||||
dashedName: use-the-map-method-to-extract-data-from-an-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Finora abbiamo imparato come utilizzare funzioni pure per evitare effetti collaterali in un programma. Inoltre, abbiamo visto i vantaggi di avere una funzione che dipende solo dai suoi argomenti di input.
|
||||
|
||||
Questo è solo l'inizio. Come suggerisce il nome, la programmazione funzionale è incentrata su una teoria delle funzioni.
|
||||
|
||||
Sarebbe sensato poterle trasmettere come argomenti ad altre funzioni, e restituire una funzione da un'altra funzione. Le funzioni sono considerate <dfn>oggetti di prima classe</dfn> in JavaScript, il che significa che possono essere utilizzati come qualsiasi altro oggetto. Possono essere salvate in variabili, memorizzate in un oggetto, o passate come argomenti di un'altra funzione.
|
||||
|
||||
Cominciamo con alcune semplici funzioni che operano sugli array, che sono metodi del prototipo dell'oggetto array. In questo esercizio stiamo guardando `Array.prototype.map()`, o più semplicemente `map`.
|
||||
|
||||
Il metodo `map` itera attraverso ogni elemento di un array e restituisce un nuovo array contenente i risultati della chiamata della funzione di callback su ogni elemento. Lo fa senza mutare l'array originale.
|
||||
|
||||
Quando viene utilizzata la callback, le sono passati tre argomenti. Il primo argomento è l'elemento che è correntemente in fase di elaborazione. Il secondo è l'indice di quell'elemento e il terzo è l'array su cui è stato chiamato il metodo `map`.
|
||||
|
||||
Qui sotto trovi un esempio d'uso del metodo `map` sull'array `users` che restituisce un nuovo array contenente come elementi solo i nomi degli utenti. Per semplicità, l'esempio utilizza solo il primo argomento della callback.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const names = users.map(user => user.name);
|
||||
console.log(names);
|
||||
```
|
||||
|
||||
La console visualizzerà il valore `[ 'John', 'Amy', 'camperCat' ]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
L'array `watchList` contiene oggetti con informazioni su diversi film. Usa `map` su `watchList` per assegnare un nuovo array di oggetti con le sole chiavi `title` e `rating` alla variabile `ratings`. Il codice nell'editor al momento utilizza un ciclo `for` per farlo, quindi dovresti sostituire il ciclo con la tua espressione `map`.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `watchList` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(
|
||||
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
|
||||
);
|
||||
```
|
||||
|
||||
Il tuo codice non dovrebbe utilizzare un ciclo `for`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/));
|
||||
```
|
||||
|
||||
Il tuo codice dovrebbe utilizzare il metodo `map`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.map/g));
|
||||
```
|
||||
|
||||
`ratings` dovrebbe essere uguale 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, [
|
||||
{ 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' }
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// 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, Elliot 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"
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var ratings = [];
|
||||
for(var i=0; i < watchList.length; i++){
|
||||
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(JSON.stringify(ratings));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// 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, Elliot 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"
|
||||
}
|
||||
];
|
||||
|
||||
var ratings = watchList.map(function(movie) {
|
||||
return {
|
||||
title: movie["Title"],
|
||||
rating: movie["imdbRating"]
|
||||
}
|
||||
});
|
||||
```
|
@ -0,0 +1,345 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b68
|
||||
title: Usare il metodo reduce per analizzare i dati
|
||||
challengeType: 1
|
||||
forumTopicId: 301313
|
||||
dashedName: use-the-reduce-method-to-analyze-data
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`Array.prototype.reduce()`, o semplicemente `reduce()`, è la più generale di tutte le operazioni sugli array in JavaScript. È possibile risolvere quasi tutti i problemi di elaborazione di array utilizzando il metodo `reduce`.
|
||||
|
||||
Il metodo `reduce` consente forme più generali di elaborazione di array, ed è possibile mostrare che sia `filter` che `map` possono essere derivati come applicazioni speciali di `reduce`. Il metodo `reduce` iterate attraverso ogni elemento di un array e restituisce un singolo valore (cioè una stringa, un numero, un oggetto, un array...). Questo si ottiene tramite una funzione di callback che viene chiamata ad ogni iterazione.
|
||||
|
||||
La funzione callback accetta quattro argomenti. Il primo argomento è conosciuto come l'accumulatore, al quale viene assegnato il valore di ritorno della funzione di callback dall'iterazione precedente, il secondo è l'elemento attuale in fase di elaborazione, il terzo è l'indice di quell'elemento e il quarto è l'array su cui `reduce` è chiamato.
|
||||
|
||||
Oltre alla funzione di callback, `reduce` ha un parametro aggiuntivo che prende un valore iniziale per l'accumulatore. Se questo secondo parametro non è utilizzato, la prima iterazione è saltata e alla seconda iterazione viene passato il primo elemento dell'array come accumulatore.
|
||||
|
||||
Qui sotto trovi un esempio che utilizza `reduce` sull'array `users` per restituire la somma di tutte le età degli utenti. Per semplicità, l'esempio utilizza solo il primo e il secondo argomento.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
|
||||
console.log(sumOfAges);
|
||||
```
|
||||
|
||||
La console visualizzerà il valore `64`.
|
||||
|
||||
In quest'altro esempio, guarda come può essere restituito un oggetto contenente i nomi degli utenti come proprietà con le loro età come valori.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const usersObj = users.reduce((obj, user) => {
|
||||
obj[user.name] = user.age;
|
||||
return obj;
|
||||
}, {});
|
||||
console.log(usersObj);
|
||||
```
|
||||
|
||||
La console visualizzerà il valore `{ John: 34, Amy: 20, camperCat: 10 }`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
La variabile `watchList` contiene una serie di oggetti con informazioni su diversi film. Usa `reduce` per trovare la valutazione IMDB media dei film diretti da `Christopher Nolan`. Ricorda dalle sfide precedenti come utilizzare `filter` sui dati e come utilizzare `map` su di essi per estrarre quello che ti serve. Potresti aver bisogno di creare altre variabili e restituire la valutazione media dalla funzione `getRating`. Nota che i valori delle valutazioni sono salvati come stringhe nell'oggetto e dovranno essere convertiti in numeri prima di essere utilizzati in qualsiasi operazione matematica.
|
||||
|
||||
# --hints--
|
||||
|
||||
La variabile `watchList` non dovrebbe cambiare.
|
||||
|
||||
```js
|
||||
assert(
|
||||
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
|
||||
);
|
||||
```
|
||||
|
||||
Il tuo codice dovrebbe usare il metodo `reduce`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.reduce/g));
|
||||
```
|
||||
|
||||
`getRating(watchList)` dovrebbe essere pari a 8.675.
|
||||
|
||||
```js
|
||||
assert(getRating(watchList) === 8.675);
|
||||
```
|
||||
|
||||
Il tuo codice non dovrebbe utilizzare un ciclo `for`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
|
||||
```
|
||||
|
||||
Il tuo codice dovrebbe restituire l'output corretto dopo aver valutato l'oggetto `watchList`.
|
||||
|
||||
```js
|
||||
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// 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, Elliot 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"
|
||||
}
|
||||
];
|
||||
|
||||
function getRating(watchList){
|
||||
// Only change code below this line
|
||||
var averageRating;
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return averageRating;
|
||||
}
|
||||
console.log(getRating(watchList));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// 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, Elliot 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"
|
||||
}
|
||||
];
|
||||
|
||||
function getRating(watchList){
|
||||
var averageRating;
|
||||
const rating = watchList
|
||||
.filter(obj => obj.Director === "Christopher Nolan")
|
||||
.map(obj => Number(obj.imdbRating));
|
||||
averageRating = rating.reduce((accum, curr) => accum + curr)/rating.length;
|
||||
return averageRating;
|
||||
}
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6f
|
||||
title: Usare il metodo some per verificare che almeno un elemento di un array soddisfi un criterio
|
||||
challengeType: 1
|
||||
forumTopicId: 301314
|
||||
dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Il metodo `some` funziona con gli array per verificare se *un qualunque* elemento supera un test particolare. Restituisce un valore booleano: `true` se uno qualsiasi dei valori soddisfa i criteri, `false` altrimenti.
|
||||
|
||||
Ad esempio, il seguente codice controllerà se almeno un elemento nell'array `numbers` è inferiore a 10:
|
||||
|
||||
```js
|
||||
var numbers = [10, 50, 8, 220, 110, 11];
|
||||
numbers.some(function(currentValue) {
|
||||
return currentValue < 10;
|
||||
});
|
||||
```
|
||||
|
||||
Il metodo `some` restituirà `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa il metodo `some` all'interno della funzione `checkPositive` per verificare se almeno un elemento in `arr` è positivo. La funzione dovrebbe restituire un valore booleano.
|
||||
|
||||
# --hints--
|
||||
|
||||
Il tuo codice dovrebbe usare il metodo `some`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.some/g));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, -4, 5])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(checkPositive([1, 2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, 4, 5])` dovrebbe restituire `true`.
|
||||
|
||||
```js
|
||||
assert(checkPositive([1, 2, 3, 4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([-1, -2, -3, -4, -5])` dovrebbe restituire `false`.
|
||||
|
||||
```js
|
||||
assert(!checkPositive([-1, -2, -3, -4, -5]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
return arr.some(elem => elem > 0);
|
||||
// Only change code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
Reference in New Issue
Block a user