TypeScript で accumulate を実装する

syakoo posted on

Python の itertools.accumulate のようなものを TypeScript で実装しました

コード

function* accumulate<T>(
  iterable: Iterable<T>,
  func: (x: T, y: T) => T,
  initial?: T
) {
  let x = initial
  if (x !== undefined) yield x

  for (let y of iterable) {
    x = x === undefined ? y : func(x, y)
    yield x
  }
}

配列やジェネレータなどの iterable から関数 func の結果を蓄積するジェネレータです。 initial には初期値を設定することができます。

Python のとは違い、演算 func にデフォルト引数はありません。

使い方

配列の累積和を取得する(初期値なし)

const xs = [1, 2, 3, 4, 5]
const sums = [...accumulate(xs, (x, y) => x + y)]
// sums = [1, 3, 6, 10, 15]

配列の累積和を取得する(初期値あり)

const xs = [1, 2, 3, 4, 5]
const sums = [...accumulate(xs, (x, y) => x + y, 100)]
// sums = [100, 101, 103, 106, 110, 115]