Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

d3.cumsum? #102

Closed
yurivish opened this issue Apr 21, 2019 · 4 comments
Closed

d3.cumsum? #102

yurivish opened this issue Apr 21, 2019 · 4 comments

Comments

@yurivish
Copy link

Taking a cumulative sum is a common function in numeric computing and I've found myself repeatedly reaching for it over the years.

[1, 2, 3, 4].reduce((a, b) => (a.push(b + (a.length ? a[a.length-1] : 0)), a), [])

It can be implemented in one line, though you can achieve better performance by copying the array and running through 1:n adding a[n-1] to a[n] inside each iteration.

@mbostock
Copy link
Member

I think I would implement this as

function cumsum(values) {
  let sum = 0;
  return Float64Array.from(values, v => sum += v);
}

so that it works with iterables. But I’d also change it to coerce to numbers, treat NaN as zero, and take an accessor.

@Fil
Copy link
Member

Fil commented Oct 18, 2019

function cumsum(values, valueof) {
  var sum = 0, index = 0, value;
  return Float64Array.from(values, valueof === undefined
    ? v => (sum += +v || 0)
    : v => (sum += +valueof(v, index++, values) || 0));
}

(edited with Mike's suggestion)
(re-edited with index++ rather than ++index, so that valueof(d,i) starts with i=0)

https://observablehq.com/@fil/cumsum

Fil added a commit that referenced this issue Oct 18, 2019
@Fil Fil mentioned this issue Oct 18, 2019
@Fil
Copy link
Member

Fil commented Oct 19, 2019

Documentation: https://observablehq.com/d/918b60f6963a81e1

@mbostock
Copy link
Member

mbostock commented Nov 9, 2019

Added in 2.4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants