2021-06-15 00:49:18 -07:00
---
id: 594810f028c0303b75339ace
2022-02-04 00:46:32 +05:30
title: Fabbrica di accumulatori
2021-06-15 00:49:18 -07:00
challengeType: 5
forumTopicId: 302222
dashedName: accumulator-factory
---
# --description--
2022-02-04 00:46:32 +05:30
Un problema posto da [Paul Graham ](https://it.wikipedia.org/wiki/Paul_Graham_(informatico )) è quello di creare una funzione che accetta un singolo argomento (numerico) e che restituisce un'altra funzione che è un accumulatore. A sua volta anche la funzione accumulatrice restituita accetta un singolo argomento numerico, e restituisce la somma di tutti i valori numerici passati finora a quell'accumulatore (incluso il valore iniziale passato quando l'accumulatore è stato creato).
2021-06-15 00:49:18 -07:00
# --instructions--
2022-02-04 00:46:32 +05:30
Crea una funzione che prende un numero $n$ e genera funzioni accumulatrici che restituiscono la somma di ogni numero passato a loro.
2021-06-15 00:49:18 -07:00
2022-02-04 00:46:32 +05:30
**Regole:**
2021-06-15 00:49:18 -07:00
2022-02-04 00:46:32 +05:30
Non usare variabili globali.
2021-06-15 00:49:18 -07:00
2022-02-04 00:46:32 +05:30
**Suggerimento:**
2021-06-15 00:49:18 -07:00
2022-02-04 00:46:32 +05:30
La chiusura salva lo stato esterno.
2021-06-15 00:49:18 -07:00
# --hints--
2022-02-04 00:46:32 +05:30
`accumulator` dovrebbe essere una funzione.
2021-06-15 00:49:18 -07:00
```js
assert(typeof accumulator === 'function');
```
2022-02-04 00:46:32 +05:30
`accumulator(0)` dovrebbe restituire una funzione.
2021-06-15 00:49:18 -07:00
```js
assert(typeof accumulator(0) === 'function');
```
2022-02-04 00:46:32 +05:30
`accumulator(0)(2)` dovrebbe restituire un numero.
2021-06-15 00:49:18 -07:00
```js
assert(typeof accumulator(0)(2) === 'number');
```
2022-02-04 00:46:32 +05:30
Passare i valori 3, -4, 1.5, e 5 dovrebbe restituire 5.5.
2021-06-15 00:49:18 -07:00
```js
assert(testFn(5) === 5.5);
```
# --seed--
## --after-user-code--
```js
const testFn = typeof accumulator(3) === 'function' & & accumulator(3);
if (testFn) {
testFn(-4);
testFn(1.5);
}
```
## --seed-contents--
```js
function accumulator(sum) {
}
```
# --solutions--
```js
function accumulator(sum) {
return function(n) {
return sum += n;
};
}
```