FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

feat(array): add getMaxFromArr in array by wenzi0github · Pull Request #8 · wenzi0github/algorithm-by-javascript · GitHub

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .ts  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
15 changes: 14 additions & 1 deletion __tests__/array.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mergeSortedArray, removeDuplicates, binarySearch } from '../src/libs/array';
import { mergeSortedArray, removeDuplicates, binarySearch, getMaxFromArr } from '../src/libs/array';

describe('test mergeSortedArray util', () => {
test('should get sorted array', () => {
Expand Down Expand Up @@ -34,3 +34,16 @@ describe('test binarySearch util', () => {
expect(binarySearch([1, 3, 5, 7], 2)).toBe(-1);
});
});

describe('test getMaxFromArr', () => {
test('should get top one max value', () => {
expect(getMaxFromArr([4, 3, 2, 5])).toEqual([5]);
});
test('should get top two max value', () => {
expect(getMaxFromArr([4, 3, 2, 5], 2)).toEqual([5, 4]);
});
test('should get null array when limit less then 1 or arr length less 1', () => {
expect(getMaxFromArr([4, 3, 2, 5], 0)).toEqual([]);
expect(getMaxFromArr([])).toEqual([]);
});
});
25 changes: 25 additions & 0 deletions src/libs/array.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,28 @@ export const binarySearch = <T = number>(arr: T[], value: T): number => {
}
return -1;
};

/**
* 从数组中获取最大的几个数据
* @param arr 数字
* @param limit 要找到几个数据
*/
export const getMaxFromArr = <T = number>(arr: T[], limit = 1): T[] => {
const { length } = arr;

if (limit <= 0 || length === 0) {
return [];
}
if (limit === 1) {
let maxValue = arr[0];
for (let i = 1; i < length; i++) {
if (arr[i] > maxValue) {
maxValue = arr[i];
}
}
return [maxValue];
}
const tempArr = arr.concat();
tempArr.sort((a, b) => (a >= b ? -1 : 1));
return tempArr.slice(0, limit);
};

Back | FazBrowse Home | New Git URL