Skip to content
  • Sponsor TheAlgorithms/TypeScript

  • Notifications You must be signed in to change notification settings
  • Fork 416
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 12fa80b

Browse files
Psytewpatrickwestervelt
and
patrickwestervelt
authoredOct 16, 2022
algorithm: find min (#61)
Co-authored-by: patrickwestervelt <pwestervelt3@gatech.edu>
1 parent 78773bc commit 12fa80b

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
 

‎Maths/FindMin.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function FindMin
3+
* @description Find the minimum in an array of numbers.
4+
* @param {Number[]} nums - An array of numbers.
5+
* @return {Number} - The minimum.
6+
* @see https://infinitbility.com/how-to-find-minimum-value-in-array-in-typescript/
7+
* @example FindMin([1,2,3,4,5]) = 1
8+
* @example FindMin([87,6,13,999]) = 6
9+
* @example FindMin([0.8,0.2,0.3,0.5]) = 0.2
10+
* @example FindMin([1,0.1,-1]) = -1
11+
*/
12+
export const FindMin = (nums: number[]): number => {
13+
if (nums.length === 0) {
14+
throw new Error("array must have length of 1 or greater");
15+
}
16+
17+
let minimumSeen: number = nums[0];
18+
for (const num of nums) {
19+
if (num < minimumSeen) {
20+
minimumSeen = num;
21+
}
22+
}
23+
24+
return minimumSeen;
25+
};

‎Maths/test/FindMin.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { FindMin } from "../FindMin";
2+
3+
describe("FindMin", () => {
4+
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]])(
5+
"of this array should be %i",
6+
(nums, expected) => {
7+
expect(FindMin(nums)).toBe(expected);
8+
},
9+
);
10+
11+
test("of arrays with length 0 should error", () => {
12+
expect(() => FindMin([])).toThrowError(
13+
"array must have length of 1 or greater",
14+
);
15+
});
16+
});

0 commit comments

Comments
 (0)