2018-09-30 23:01:58 +01:00
---
title: Accumulator factory
id: 594810f028c0303b75339ace
challengeType: 5
2019-08-05 09:17:33 -07:00
forumTopicId: 302222
2018-09-30 23:01:58 +01:00
---
## Description
< section id = 'description' >
2019-05-23 13:57:59 +09:00
A problem posed by < a href = 'https://en.wikipedia.org/wiki/Paul_Graham_(programmer)' target = '_blank' > Paul Graham< / a > 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).
2018-09-30 23:01:58 +01:00
< / section >
## Instructions
< section id = 'instructions' >
2019-03-01 17:10:50 +09:00
Create a function that takes a number $n$ and generates accumulator functions that return the sum of every number ever passed to them.
2019-06-14 20:04:16 +09:00
< strong > Rules:< / strong >
2019-03-01 17:10:50 +09:00
Do not use global variables.
2019-06-14 20:04:16 +09:00
< strong > Hint:< / strong >
2019-03-01 17:10:50 +09:00
Closures save outer state.
2018-09-30 23:01:58 +01:00
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 14:37:37 +01:00
tests:
2019-11-20 07:01:31 -08:00
- text: < code > accumulator</ code > should be a function.
2019-07-26 05:24:52 -07:00
testString: assert(typeof accumulator === 'function');
2018-10-04 14:37:37 +01:00
- text: < code > accumulator(0)</ code > should return a function.
2019-07-26 05:24:52 -07:00
testString: assert(typeof accumulator(0) === 'function');
2018-10-04 14:37:37 +01:00
- text: < code > accumulator(0)(2)</ code > should return a number.
2019-07-26 05:24:52 -07:00
testString: assert(typeof accumulator(0)(2) === 'number');
2018-10-20 21:02:47 +03:00
- text: Passing in the values 3, -4, 1.5, and 5 should return 5.5.
2019-07-26 05:24:52 -07:00
testString: assert(testFn(5) === 5.5);
2018-09-30 23:01:58 +01:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```js
2019-02-24 19:04:29 +09:00
function accumulator(sum) {
2018-09-30 23:01:58 +01:00
// Good luck!
}
```
< / div >
### After Test
< div id = 'js-teardown' >
```js
2018-10-20 21:02:47 +03:00
const testFn = typeof accumulator(3) === 'function' & & accumulator(3);
if (testFn) {
testFn(-4);
testFn(1.5);
}
2018-09-30 23:01:58 +01:00
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
2019-02-26 17:07:07 +09:00
function accumulator(sum) {
2019-03-01 17:10:50 +09:00
return function(n) {
2018-09-30 23:01:58 +01:00
return sum += n;
};
}
```
< / section >