Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Data-Structures/Array/BasicPrefixSum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Computes prefix sums for a numeric array.
* Example: [2, 3, 5] → [2, 5, 10]
* @param {number[]} arr
* @returns {number[]} Prefix sum array
* @throws {TypeError} if input is not a numeric array
*/
export const basicPrefixSum = (arr) => {
if (!Array.isArray(arr)) {
throw new TypeError('Input must be an array')
}

if (!arr.every((item) => typeof item === 'number')) {
throw new TypeError('All elements must be numbers')
}

const prefix = []
let sum = 0
for (const num of arr) {
sum += num
prefix.push(sum)
}
return prefix
}
20 changes: 20 additions & 0 deletions Data-Structures/Array/test/BasicPrefixSum.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, it, expect } from 'vitest'
import { basicPrefixSum } from '../BasicPrefixSum.js'

describe('basicPrefixSum', () => {
it('computes prefix sums correctly', () => {
expect(basicPrefixSum([1, 2, 3, 4])).toEqual([1, 3, 6, 10])
})

it('returns an empty array for empty input', () => {
expect(basicPrefixSum([])).toEqual([])
})

it('throws an error if input is not an array', () => {
expect(() => basicPrefixSum('abc')).toThrow(TypeError)
})

it('throws an error if array contains non-numeric elements', () => {
expect(() => basicPrefixSum([1, '2', 3])).toThrow(TypeError)
})
})