Skip to content
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

algorithm: average/mean #30

Merged
merged 5 commits into from
Oct 9, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
21 changes: 21 additions & 0 deletions Maths/AverageMean.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @function AverageMean
* @description This script will find the mean value of a array of numbers.
* @param {number[]} numbers - Array of numeric values
* @return {number} - mean of input numbers
* @see [Mean](https://en.wikipedia.org/wiki/Mean)
* @example AverageMean([1, 2, 4, 5]) = 3
* @example AverageMean([10, 40, 100, 20]) = 42.5
*/

export const AverageMean = (numbers: number[]): number => {
if (!Array.isArray(numbers) || numbers.length < 1) {
orangegrove1955 marked this conversation as resolved.
Show resolved Hide resolved
throw new TypeError("Invalid Input");
}

// This loop sums all values in the 'numbers' array using an array reducer
const sum = numbers.reduce((sum, current) => sum + current, 0);

// Divide sum by the length of the 'numbers' array.
return sum / numbers.length;
};
31 changes: 31 additions & 0 deletions Maths/test/AverageMean.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { AverageMean } from "../AverageMean";

describe("Tests for AverageMean", () => {
it("should be a function", () => {
expect(typeof AverageMean).toEqual("function");
});

it("should throw error for invalid input", () => {
expect(() => AverageMean([])).toThrow();
});

it("should return the mean of an array of consecutive numbers", () => {
const meanFunction = AverageMean([1, 2, 3, 4]);
expect(meanFunction).toBe(2.5);
});

it("should return the mean of an array of numbers", () => {
const meanFunction = AverageMean([10, 40, 100, 20]);
expect(meanFunction).toBe(42.5);
});

it("should return the mean of an array of decimal numbers", () => {
const meanFunction = AverageMean([1.3, 12.67, 99.14, 20]);
expect(meanFunction).toBe(33.2775);
});

it("should return the mean of an array of numbers, including negatives", () => {
const meanFunction = AverageMean([10, -40, 100, -20]);
expect(meanFunction).toBe(12.5);
});
});