Thanks to visit codestin.com
Credit goes to github.com

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
37 changes: 37 additions & 0 deletions PrefixSum/BasicPrefixSum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Computes the prefix sum of an array
* @param {number[]} arrayOfNumbers - Array of numbers
* @returns {number[]} - Prefix sum array
* @throws {TypeError} - If input is not a numeric array
*/
function basicPrefixSum(arrayOfNumbers) {
// Validate input
if (!Array.isArray(arrayOfNumbers)) {
throw new TypeError('Input must be an array')
}

for (let i = 0; i < arrayOfNumbers.length; i++) {
if (
typeof arrayOfNumbers[i] !== 'number' ||
!Number.isFinite(arrayOfNumbers[i])
) {
throw new TypeError('All elements must be finite numbers')
}
}

// Handle empty array
if (arrayOfNumbers.length === 0) {
return []
}

const prefixSum = new Array(arrayOfNumbers.length)
prefixSum[0] = arrayOfNumbers[0]

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

return prefixSum
}

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

describe('BasicPrefixSum', () => {
it('should compute prefix sum for normal array', () => {
const input = [1, 2, 3, 4, 5]
const expected = [1, 3, 6, 10, 15]
expect(basicPrefixSum(input)).toEqual(expected)
})

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

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

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

it('should throw TypeError for non-array input', () => {
expect(() => basicPrefixSum('not an array')).toThrow(TypeError)
expect(() => basicPrefixSum(123)).toThrow(TypeError)
expect(() => basicPrefixSum(null)).toThrow(TypeError)
})

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

it('should throw TypeError for infinite values', () => {
expect(() => basicPrefixSum([1, Infinity, 3])).toThrow(TypeError)
expect(() => basicPrefixSum([1, -Infinity, 3])).toThrow(TypeError)
expect(() => basicPrefixSum([1, NaN, 3])).toThrow(TypeError)
})
})
Loading