var arr = new Array(1000000);
arr.fill(10);
arr[5] = 1
function findOutlier(integers){
//your code here
var test;
let i = 0;
let len = integers.length;
if ((integers[0] % 2 == 0 || integers[1] % 2 == 0) && (integers[2] % 2 == 0 || integers[3] % 2 == 0)) {
// outlier is odd
test = function(int) {
return int % 2 !== 0;
}
} else {
// outlier is even
test = function(int) {
return int % 2 === 0;
}
}
for(i;i < len;i++) {
if (test(integers[i])) {
return integers[i]
}
}
}
findOutlier(arr);
function findOutlier(int){
var even = int.filter(a=>a%2==0);
var odd = int.filter(a=>a%2!==0);
return even.length==1? even[0] : odd[0];
}
findOutlier(arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
looping | |
filtering |
Test name | Executions per second |
---|---|
looping | 4339432.5 Ops/sec |
filtering | 9.9 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Definition
The benchmark definition defines a JavaScript function findOutlier
that takes an array of integers as input. The function is supposed to find the outlier in the array, which is the number that does not fit the pattern (either all even or all odd numbers).
Options Compared
There are two options being compared:
filter()
method to create two arrays, one for even numbers and one for odd numbers, and then returns the first element of the array with only one element.Pros and Cons
Library
None of the benchmarked code uses any external libraries. However, some browsers may have their own internal optimizations or implementation details that can affect the performance of the filter()
method.
Special JS Features or Syntax
There are no special JavaScript features or syntax being used in this benchmark. The code is straightforward and uses standard JavaScript concepts.
Other Considerations
Alternatives
Other alternatives for finding the outlier in an array include:
However, these alternatives are likely to be slower or more complex than the simple filtering approach used in the benchmark.