Skip to content

Commit

Permalink
Implement array functions
Browse files Browse the repository at this point in the history
- sum: sum of all elements in the array
- product: product of all elements in the array
- average: average of all elements in the array
  • Loading branch information
kitsuyui committed Dec 27, 2024
1 parent e2d2c2d commit f59e423
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
37 changes: 37 additions & 0 deletions packages/mymath/src/array/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { describe, expect, it, jest } from '@jest/globals'

import { average, product, sum } from './index'

describe('sum', () => {
it('should return sum of all values', () => {
expect(sum([1, 2, 3, 4])).toBe(10)
})

it('should return 0 for []', () => {
expect(sum([])).toBe(0)
})
})

describe('product', () => {
it('should return product of all values', () => {
expect(product([1, 2, 3, 4])).toBe(24)
})

it('should return 1 for []', () => {
expect(product([])).toBe(1)
})
})

describe('average', () => {
it('should return average of all values', () => {
expect(average([1, 2, 3, 4])).toBe(2.5)
})

it('should return 0 for []', () => {
expect(average([])).toBe(0)
})

it('should return 5 for [] and 5', () => {
expect(average([], 5)).toBe(5)
})
})
44 changes: 44 additions & 0 deletions packages/mymath/src/array/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Sum of all values in the array
* Example: sum([1, 2, 3, 4]) => 10
* If the array is empty, it returns 0 (0 is identity element for addition)
* @param values
* @returns sum of all values
*/
export const sum = (values: number[]): number => {
let sum = 0
for (const value of values) {
sum += value
}
return sum
}

/**
* Product of all values in the array
* Example: product([1, 2, 3, 4]) => 24
* If the array is empty, it returns 1 (1 is identity element for multiplication)
* @param values
* @returns product of all values
*/
export const product = (values: number[]): number => {
let product = 1
for (const value of values) {
product *= value
}
return product
}

/**
* Average of all values in the array
* Example: average([1, 2, 3, 4]) => 2.5
* If the array is empty, it returns 0 or the defaultValue
* @param values
* @param defaultValue
* @returns average of all values
*/
export const average = (values: number[], defaultValue?: number): number => {
if (values.length === 0) {
return defaultValue || 0
}
return sum(values) / values.length
}

0 comments on commit f59e423

Please sign in to comment.