diff --git a/packages/mymath/src/array/index.spec.ts b/packages/mymath/src/array/index.spec.ts new file mode 100644 index 00000000..874d9f6d --- /dev/null +++ b/packages/mymath/src/array/index.spec.ts @@ -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) + }) +}) diff --git a/packages/mymath/src/array/index.ts b/packages/mymath/src/array/index.ts new file mode 100644 index 00000000..bbbaee7d --- /dev/null +++ b/packages/mymath/src/array/index.ts @@ -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 +}