1.6 KiB
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
594810f028c0303b75339ace | Fabbrica di accumulatori | 1 | 302222 | accumulator-factory |
--description--
Un problema posto da Paul Graham è quello di creare una funzione che prende 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).
--instructions--
Crea una funzione che prende un numero n
e genera funzioni accumulatrici che restituiscono la somma di ogni numero passato a loro.
Regole:
Non usare variabili globali.
Suggerimento:
La chiusura salva lo stato esterno.
--hints--
accumulator
dovrebbe essere una funzione.
assert(typeof accumulator === 'function');
accumulator(0)
dovrebbe restituire una funzione.
assert(typeof accumulator(0) === 'function');
accumulator(0)(2)
dovrebbe restituire un numero.
assert(typeof accumulator(0)(2) === 'number');
Passare i valori 3, -4, 1.5, e 5 dovrebbe restituire 5.5.
assert(testFn(5) === 5.5);
--seed--
--after-user-code--
const testFn = typeof accumulator(3) === 'function' && accumulator(3);
if (testFn) {
testFn(-4);
testFn(1.5);
}
--seed-contents--
function accumulator(sum) {
}
--solutions--
function accumulator(sum) {
return function(n) {
return sum += n;
};
}