Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[FEATURE]: Add Basic Prefix Sum Algorithm with Tests #1783#1799

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
Virus2hell wants to merge1 commit intoTheAlgorithms:master
base:master
Choose a base branch
Loading
fromVirus2hell:feat/add-basic-prefix-sum
Open
Show file tree
Hide file tree
Changes fromall 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 deletionsPrefixSum/BasicPrefixSum.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionsPrefixSum/BasicPrefixSum.test.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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])
})
})

[8]ページ先頭

©2009-2025 Movatter.jp