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: find min #61

Merged
merged 1 commit into from
Oct 16, 2022
Merged
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
25 changes: 25 additions & 0 deletions Maths/FindMin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @function FindMin
* @description Find the minimum in an array of numbers.
* @param {Number[]} nums - An array of numbers.
* @return {Number} - The minimum.
* @see https://infinitbility.com/how-to-find-minimum-value-in-array-in-typescript/
* @example FindMin([1,2,3,4,5]) = 1
* @example FindMin([87,6,13,999]) = 6
* @example FindMin([0.8,0.2,0.3,0.5]) = 0.2
* @example FindMin([1,0.1,-1]) = -1
*/
export const FindMin = (nums: number[]): number => {
if (nums.length === 0) {
throw new Error("array must have length of 1 or greater");
}

let minimumSeen: number = nums[0];
for (const num of nums) {
if (num < minimumSeen) {
minimumSeen = num;
}
}

return minimumSeen;
};
16 changes: 16 additions & 0 deletions Maths/test/FindMin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { FindMin } from "../FindMin";

describe("FindMin", () => {
test.each([[[1,2,3,4,5,6], 1], [[87,6,13,999], 6], [[0.8,0.2,0.3,0.5], 0.2], [[1,0.1,-1], -1]])(
"of this array should be %i",
(nums, expected) => {
expect(FindMin(nums)).toBe(expected);
},
);

test("of arrays with length 0 should error", () => {
expect(() => FindMin([])).toThrowError(
"array must have length of 1 or greater",
);
});
});