Skip to content

feat: add BasicPrefixSum algorithm and tests #1787

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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`, () => {
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`, () => {
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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy