Skip to content

Commit 1cca986

Browse files
committed
feat: add BasicPrefixSum algorithm and tests
1 parent 1d252d7 commit 1cca986

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

PrefixSum/BasicPrefixSum.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function prefixSum(arr) {
2+
if (!Array.isArray(arr) || arr.some((num) => typeof num !== 'number')) {
3+
throw new TypeError(`Input must be an array of numbers`)
4+
}
5+
6+
const pSum = []
7+
8+
let sum = 0
9+
10+
for (const num of arr) {
11+
sum += num
12+
pSum.push(sum)
13+
}
14+
15+
return pSum
16+
}
17+
18+
export { prefixSum }
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { prefixSum } from '../BasicPrefixSum.js'
2+
import { describe, it, expect } from 'vitest'
3+
4+
describe('prefixSum', () => {
5+
it(`Should return computed prefix sum array for a passed input array`, () => {
6+
expect(prefixSum([3, 6, 9, 15])).toEqual([3, 9, 18, 33])
7+
expect(prefixSum([0, 5, -2, 4])).toEqual([0, 5, 3, 7])
8+
})
9+
10+
it(`Should return empty array when passed input array is empty`, () => {
11+
expect(prefixSum([])).toEqual([])
12+
})
13+
14+
it(`should throw TypeError if input is not an array of numbers`, () => {
15+
expect(() => prefixSum('array')).toThrow(TypeError)
16+
expect(() => prefixSum(1)).toThrow(TypeError)
17+
expect(() => prefixSum([1, '2'])).toThrow(TypeError)
18+
expect(() => prefixSum([1, true])).toThrow(TypeError)
19+
expect(() => prefixSum([{}, 2])).toThrow(TypeError)
20+
})
21+
})

0 commit comments

Comments
 (0)