Skip to content

Commit 6534323

Browse files
committed
feat: add BasicPrefixSum algorithm and tests
1 parent 012f23d commit 6534323

File tree

4 files changed

+375
-262
lines changed

4 files changed

+375
-262
lines changed

PrefixSum/BasicPrefixSum.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,19 @@
77
* @throws {TypeError} - If input is not an array of numbers.
88
*/
99
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-
}
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+
}
1414

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;
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
2222
}
2323

2424
// Export the function for use in other modules
25-
module.exports = basicPrefixSum;
25+
module.exports = basicPrefixSum

PrefixSum/test/BasicPrefixSum.test.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import basicPrefixSum from '../BasicPrefixSum'
1+
import basicPrefixSum from '../BasicPrefixSum'
22

33
describe('basicPrefixSum', () => {
44
it('computes correct prefix sums for normal arrays', () => {
@@ -19,4 +19,4 @@ describe('basicPrefixSum', () => {
1919
expect(() => basicPrefixSum(null)).toThrow(TypeError)
2020
expect(() => basicPrefixSum(undefined)).toThrow(TypeError)
2121
})
22-
})
22+
})

0 commit comments

Comments
 (0)