2018-09-30 22:01:58 +00:00
---
id: 594810f028c0303b75339ace
2020-11-27 18:02:05 +00:00
title: Accumulator factory
2018-09-30 22:01:58 +00:00
challengeType: 5
2019-08-05 16:17:33 +00:00
forumTopicId: 302222
2021-01-13 02:31:00 +00:00
dashedName: accumulator-factory
2018-09-30 22:01:58 +00:00
---
2020-11-27 18:02:05 +00:00
# --description--
A problem posed by [Paul Graham ](https://en.wikipedia.org/wiki/Paul_Graham_(programmer )) is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
# --instructions--
2018-09-30 22:01:58 +00:00
2019-03-01 08:10:50 +00:00
Create a function that takes a number $n$ and generates accumulator functions that return the sum of every number ever passed to them.
2020-11-27 18:02:05 +00:00
**Rules:**
2019-03-01 08:10:50 +00:00
Do not use global variables.
2020-11-27 18:02:05 +00:00
**Hint:**
2019-03-01 08:10:50 +00:00
Closures save outer state.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --hints--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`accumulator` should be a function.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert(typeof accumulator === 'function');
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`accumulator(0)` should return a function.
2018-09-30 22:01:58 +00:00
```js
2020-11-27 18:02:05 +00:00
assert(typeof accumulator(0) === 'function');
```
2020-09-15 16:57:40 +00:00
2020-11-27 18:02:05 +00:00
`accumulator(0)(2)` should return a number.
```js
assert(typeof accumulator(0)(2) === 'number');
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
Passing in the values 3, -4, 1.5, and 5 should return 5.5.
```js
assert(testFn(5) === 5.5);
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --seed--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
## --after-user-code--
2018-09-30 22:01:58 +00:00
```js
2018-10-20 18:02:47 +00:00
const testFn = typeof accumulator(3) === 'function' & & accumulator(3);
if (testFn) {
testFn(-4);
testFn(1.5);
}
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
## --seed-contents--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
function accumulator(sum) {
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
}
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --solutions--
2018-09-30 22:01:58 +00:00
```js
2019-02-26 08:07:07 +00:00
function accumulator(sum) {
2019-03-01 08:10:50 +00:00
return function(n) {
2018-09-30 22:01:58 +00:00
return sum += n;
};
}
```