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
18 changes: 18 additions & 0 deletions PrefixSum/BasicPrefixSum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function prefixSum(arr) {
if (!Array.isArray(arr) || arr.some((num) => typeof num !== 'number')) {
throw new TypeError(`Input must be an array of numbers`)
}

const pSum = []

let sum = 0

for (const num of arr) {
sum += num
pSum.push(sum)
}

return pSum
}

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

describe('prefixSum', () => {
it(`Should return computed prefix sum array for a passed input array`, () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"should" does not have to be capitalized

expect(prefixSum([3, 6, 9, 15])).toEqual([3, 9, 18, 33])
expect(prefixSum([0, 5, -2, 4])).toEqual([0, 5, 3, 7])
})

it(`Should return empty array when passed input array is empty`, () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"should" does not have to be capitalized

expect(prefixSum([])).toEqual([])
})

it(`should throw TypeError if input is not an array of numbers`, () => {
expect(() => prefixSum('array')).toThrow(TypeError)
expect(() => prefixSum(1)).toThrow(TypeError)
expect(() => prefixSum([1, '2'])).toThrow(TypeError)
expect(() => prefixSum([1, true])).toThrow(TypeError)
expect(() => prefixSum([{}, 2])).toThrow(TypeError)
})
})
Loading