Files
freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/rosetta-code/accumulator-factory.english.md
Randell Dawson c25916c9a2 fix(curriculum): changed test text to use should for Coding Interview Prep - part 2 of 2 (#37766)
* fix: changed test text to use should

* fix: corrected typo

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: removed extra period

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: removed extra period

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: removed extra period

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: removed extra period

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: corrected typo

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>
2019-11-20 10:01:31 -05:00

1.9 KiB

title, id, challengeType, forumTopicId
title id challengeType forumTopicId
Accumulator factory 594810f028c0303b75339ace 5 302222

Description

A problem posed by Paul Graham 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

Create a function that takes a number $n$ and generates accumulator functions that return the sum of every number ever passed to them. Rules: Do not use global variables. Hint: Closures save outer state.

Tests

tests:
  - text: <code>accumulator</code> should be a function.
    testString: assert(typeof accumulator === 'function');
  - text: <code>accumulator(0)</code> should return a function.
    testString: assert(typeof accumulator(0) === 'function');
  - text: <code>accumulator(0)(2)</code> should return a number.
    testString: assert(typeof accumulator(0)(2) === 'number');
  - text: Passing in the values 3, -4, 1.5, and 5 should return 5.5.
    testString: assert(testFn(5) === 5.5);

Challenge Seed

function accumulator(sum) {
  // Good luck!
}

After Test

const testFn = typeof accumulator(3) === 'function' && accumulator(3);
if (testFn) {
  testFn(-4);
  testFn(1.5);
}

Solution

function accumulator(sum) {
  return function(n) {
    return sum += n;
  };
}