Skip to content

Latest commit

 

History

History
27 lines (22 loc) · 1.05 KB

accumulate.md

File metadata and controls

27 lines (22 loc) · 1.05 KB
title tags author_title author_url author_image_url description image
accumulate
math,array,beginner
Deepak Vishwakarma
Implementation of "accumulate" in typescript, javascript and deno.

TS JS Deno

Returns an array of partial sums.

Use Array.prototype.reduce(), Array.prototype.slice(-1) and the unary + operator to add each value to the unary array containing the previous sum.

const accumulate = (...nums: number[]): number[] =>
  nums.reduce((acc: number[], n) => [...acc, n + +acc.slice(-1)], []);
accumulate(1, 2, 3, 4); // [1, 3, 6, 10]
accumulate(...[1, 2, 3, 4]); // [1, 3, 6, 10]