Skip to content
Open
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
30 changes: 30 additions & 0 deletions PrefixSum/BasicPrefixSum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* BasicPrefixSum.js
* Implementation of Prefix Sum array.
*
* @param {number[]} arr - Input array of numbers.
* @returns {number[]} Prefix sum array.
* @throws {TypeError} If input is not an array of numbers.
*
* Explanation:
* Given [1,2,3,4], returns [1,3,6,10]
*/

export function basicPrefixSum(arr) {
// Validate input
if (!Array.isArray(arr) || arr.some((x) => typeof x !== 'number')) {
throw new TypeError('Input must be an array of numbers')
}

// Handle empty array
if (arr.length === 0) return []

const prefix = new Array(arr.length)
prefix[0] = arr[0]

for (let i = 1; i < arr.length; i++) {
prefix[i] = prefix[i - 1] + arr[i]
}

return prefix
}
26 changes: 26 additions & 0 deletions PrefixSum/BasicPrefixSum.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, it, expect } from 'vitest'
import { basicPrefixSum } from './BasicPrefixSum.js'

describe('Basic Prefix Sum', () => {
it('should compute prefix sum of a normal array', () => {
const arr = [1, 2, 3, 4]
const expected = [1, 3, 6, 10]
expect(basicPrefixSum(arr)).toEqual(expected)
})

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

it('should throw TypeError for non-numeric array', () => {
expect(() => basicPrefixSum([1, 'a', 3])).toThrow(TypeError)
})

it('should handle single element array', () => {
expect(basicPrefixSum([5])).toEqual([5])
})

it('should handle negative numbers', () => {
expect(basicPrefixSum([-1, -2, -3])).toEqual([-1, -3, -6])
})
})