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 numbers
Efficiency meaning here that the method or set of methods requires the least amount of computational resources and returns either true
or false
in the least amount of time
Context: Condition at if
within a for
loop which could require from thousands to hundreds of thousands of iterations to return a result; where milliseconds required to return true
or false
as to Number
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
*/
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…