freeCodeCamp/curriculum/challenges/japanese/10-coding-interview-prep/rosetta-code/accumulator-factory.md

1.6 KiB

id title challengeType forumTopicId dashedName
594810f028c0303b75339ace アキュムレータ・ファクトリ 1 302222 accumulator-factory

--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. 返されたアキュムレータ関数は、1つの数値引数を取り、これまでにアキュムレータに渡されたすべての数値の合計 (アキュムレータが作成されたときに渡された初期値を含む) を返します。

--instructions--

n を取って、渡されたすべての数値の合計を返すアキュムレータ関数を生成する関数を作成します。

ルール:

グローバル変数を使用しないでください。

ヒント:

クロージャは外的な状態を保存します。

--hints--

accumulator という関数です。

assert(typeof accumulator === 'function');

accumulator(0) は関数を返します。

assert(typeof accumulator(0) === 'function');

accumulator(0)(2) は数字を返します。

assert(typeof accumulator(0)(2) === 'number');

3、-4、1.5、5の値が渡されると、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;
  };
}