Skip to content
Open
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
18 changes: 18 additions & 0 deletions 747.largest-number-at-least-twice-of-others.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* URL of this problem
* https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/
*
* @param {number[]} nums
* @return {number}
*/

var dominantIndex = function (nums) {
// Sort nums in a descending order
const SortedNums = [...nums].sort((a, b) => b - a);

if (SortedNums[0] / 2 >= SortedNums[1]) {
return nums.indexOf(SortedNums[0]);
}
return -1;
};

module.exports = dominantIndex;
25 changes: 25 additions & 0 deletions dominantIndex.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const dominantIndex = require("./747.largest-number-at-least-twice-of-others");

test("Return the index of the largest number in the array", () => {
expect(dominantIndex([3, 6, 1, 0])).toBe(1);
});

test("Return -1 if the largest integer is not at least twice as much as every other number in the array", () => {
expect(dominantIndex([1, 2, 3, 4])).toBe(-1);
});

test("Return -1 if the array is empty", () => {
expect(dominantIndex([])).toBe(-1);
});

test("Return -1 if the array is empty", () => {
expect(dominantIndex([])).toBe(-1);
});

test("Return the index of Infinity in the array if there is", () => {
expect(dominantIndex([3, 6, 1, 0, Infinity])).toBe(4);
});

test("Return the index of the largest number in the array with -Infinity", () => {
expect(dominantIndex([3, 6, 1, 0, -Infinity])).toBe(1);
});