Given a number n
, a minimum number min
, a maximum number max
, what is the most efficient method to determine
Number
n
is or is not within range , inclusive of ,min
-max
Number
n
does or does not contain duplicate numbersEfficiency meaning here that the method or set of methods requires the least amount of computational resources and returns either
true
orfalse
in the least amount of timeContext: Condition at
if
within afor
loop which could require from thousands to hundreds of thousands of iterations to return a result; where milliseconds required to returntrue
orfalse
as toNumber
check could affect performance
At Profiles
panel at DevTools
on a collection of 71,3307
items iterated, RegExp
below was listed as using 27.2ms
of total 1097.3ms
to complete loop . At a collection of 836,7628
items iterated RegExp
below used 193.5ms
within total of 11285.3ms
.
Requirement: Most efficient method to return Boolean
true
or false
given above parameters , within the least amount of time.
Note: Solution does not have to be limited to RegExp
; used below as the pattern returned expected results.
Current js
utilizing RegExp
re
, RegExp.protype.test()
var min = 2
, max = 7
, re = new RegExp("[" + min + "-" + max + "](.)(?!=\1)", "g")
, arr = [81, 35, 22, 45, 49];
for (var i = 0; i < arr.length; i++) {
console.log(re.test(arr[i]), i, arr[i])
/*
false 0 81
true 1 35
false 2 22
true 3 45
false 4 49
*/
}