2018-09-30 22:01:58 +00:00
---
title: Accumulator factory
id: 594810f028c0303b75339ace
challengeType: 5
---
## Description
< section id = 'description' >
2019-02-24 10:04:29 +00:00
Create a function that takes a single (numeric) argument and 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).
< b > Rules:< / b >
Do not use global variables.
< b > Hint:< / b >
Closures save outer state.
2018-09-30 22:01:58 +00:00
< / section >
## Instructions
< section id = 'instructions' >
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 13:37:37 +00:00
tests:
- text: < code > accumulator</ code > is a function.
2018-10-20 18:02:47 +00:00
testString: assert(typeof accumulator === 'function', '< code > accumulator< / code > is a function.');
2018-10-04 13:37:37 +00:00
- text: < code > accumulator(0)</ code > should return a function.
2018-10-20 18:02:47 +00:00
testString: assert(typeof accumulator(0) === 'function', '< code > accumulator(0)< / code > should return a function.');
2018-10-04 13:37:37 +00:00
- text: < code > accumulator(0)(2)</ code > should return a number.
2018-10-20 18:02:47 +00:00
testString: assert(typeof accumulator(0)(2) === 'number', '< code > accumulator(0)(2)< / code > should return a number.');
- text: Passing in the values 3, -4, 1.5, and 5 should return 5.5.
testString: assert(testFn(5) === 5.5, 'Passing in the values 3, -4, 1.5, and 5 should return 5.5.');
2018-09-30 22:01:58 +00:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```js
2019-02-24 10:04:29 +00:00
function accumulator(sum) {
2018-09-30 22:01:58 +00:00
// Good luck!
}
```
< / div >
### After Test
< div id = 'js-teardown' >
```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
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
2019-02-26 08:07:07 +00:00
function accumulator(sum) {
2018-09-30 22:01:58 +00:00
return function (n) {
return sum += n;
};
}
```
< / section >