Skip to content

Commit bec2ff0

Browse files
committed
feat: add basic prefix sum implementation with tests
1 parent a82c868 commit bec2ff0

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Computes prefix sums for a numeric array.
3+
* Example: [2, 3, 5] → [2, 5, 10]
4+
* @param {number[]} arr
5+
* @returns {number[]} Prefix sum array
6+
* @throws {TypeError} if input is not a numeric array
7+
*/
8+
export const basicPrefixSum = (arr) => {
9+
if (!Array.isArray(arr)) {
10+
throw new TypeError("Input must be an array");
11+
}
12+
13+
if (!arr.every((item) => typeof item === "number")) {
14+
throw new TypeError("All elements must be numbers");
15+
}
16+
17+
const prefix = [];
18+
let sum = 0;
19+
for (const num of arr) {
20+
sum += num;
21+
prefix.push(sum);
22+
}
23+
return prefix;
24+
};

0 commit comments

Comments
 (0)