Skip to content

Instantly share code, notes, and snippets.

@indiscripts
Created November 25, 2021 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indiscripts/4d2cb20fd5258f7f67b29a553a306075 to your computer and use it in GitHub Desktop.
Save indiscripts/4d2cb20fd5258f7f67b29a553a306075 to your computer and use it in GitHub Desktop.
PageToRange function
const PageToRange = function(/*uint>0*/p, q)
//----------------------------------
// Returns the 1-based range index containing page number `p`.
// (The last range supports any `p` beyond the maximum.)
// [REM] Use PageToRange.setup() to initialize the ranges.
// ---
// => uint [1 for 1st range, 2 for 2nd range...] | false [INVALID p]
{
return p > 0 && ((q=callee.Q).charCodeAt(-1+p)||q.charCodeAt(-1+q.length));
};
PageToRange.setup = function(/*uint[]*/a, r,z,p,i,t)
//----------------------------------
// Register an ordered list of page numbers (0 < a[i] < a[i+1].)
// => undef
{
const CHR = String.fromCharCode;
for
(
r=[], p=z=0, i=-1 ;
++i < a.length ;
p < (t=a[i])
&& ( r[r.length]=Array(1+t-p).join(CHR(++z)), p=t )
);
this.Q = r.join('');
}
//----------------------------------
// TEST
//----------------------------------
// `41` means "pages 1 to 41", `73` means "pages 42 to 73", etc.
const RANGES = [41,73,113,147,181,213,255,291,333,365,405,435,467,505,535,567,607,643];
// Init. (required once.)
PageToRange.setup(RANGES);
var i,arr,dt,msg;
// Loading N random numbers ranging in [1..800]
const N = 10000;
arr = (function(i,K,RND,r){ for(r=[];i--;r.push(1+~~(K*RND()))); return r;})(N,800,Math.random);
// Benchmark.
for
(
dt=0, i=arr.length ; i-- ;
arr[i]=[$.hiresTimer,PageToRange(arr[i]),dt+=$.hiresTimer][1]
);
msg = ("Total processing time: " + ~~(dt/1e3) + "ms (" + N + " numbers)\r")
+ ("Average `PageToRange` time: " + ~~(dt/N) + "µs\r\r")
+ ("First results:\r" + arr.splice(0,200).join() + '...');
alert( msg );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment