Skip to content

Commit 012f23d

Browse files
committed
added BasicPrefixSum code
1 parent 1d252d7 commit 012f23d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

PrefixSum/BasicPrefixSum.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Computes the prefix sum (cumulative sum) of an array of numbers.
3+
* For example, given [1, 2, 3], returns [1, 3, 6].
4+
*
5+
* @param {number[]} arr - The input array of numbers.
6+
* @returns {number[]} - The prefix sum array.
7+
* @throws {TypeError} - If input is not an array of numbers.
8+
*/
9+
function basicPrefixSum(arr) {
10+
// Validate input: must be an array of numbers
11+
if (!Array.isArray(arr) || !arr.every(x => typeof x === 'number')) {
12+
throw new TypeError('Input must be an array of numbers');
13+
}
14+
15+
const prefix = [];
16+
// Use reduce to calculate cumulative sum and store in prefix array
17+
arr.reduce((acc, val, index) => {
18+
prefix[index] = acc + val; // Store current sum at index
19+
return prefix[index]; // Pass current sum to next iteration
20+
}, 0);
21+
return prefix;
22+
}
23+
24+
// Export the function for use in other modules
25+
module.exports = basicPrefixSum;

PrefixSum/test/BasicPrefixSum.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import basicPrefixSum from '../BasicPrefixSum'
2+
3+
describe('basicPrefixSum', () => {
4+
it('computes correct prefix sums for normal arrays', () => {
5+
expect(basicPrefixSum([1, 2, 3, 4])).toEqual([1, 3, 6, 10])
6+
expect(basicPrefixSum([0, 0, 0])).toEqual([0, 0, 0])
7+
expect(basicPrefixSum([-1, 5, -3])).toEqual([-1, 4, 1])
8+
expect(basicPrefixSum([100])).toEqual([100]) // single element array
9+
})
10+
11+
it('returns an empty array for empty input', () => {
12+
expect(basicPrefixSum([])).toEqual([])
13+
})
14+
15+
it('throws TypeError for invalid inputs', () => {
16+
expect(() => basicPrefixSum('not an array')).toThrow(TypeError)
17+
expect(() => basicPrefixSum([1, 2, 'x'])).toThrow(TypeError)
18+
expect(() => basicPrefixSum([{}, 3])).toThrow(TypeError)
19+
expect(() => basicPrefixSum(null)).toThrow(TypeError)
20+
expect(() => basicPrefixSum(undefined)).toThrow(TypeError)
21+
})
22+
})

0 commit comments

Comments
 (0)