javascript - In an array, how do I find the closest key given a float value? -


i'm making "acceleration" array this:

acc["0100"] = 1; acc["0300"] = 2; acc["0600"] = 4; acc["0900"] = 8; acc["2000"] = 16; acc["5000"] = 32; 

and, when user presses key, start timer: this._starttick = (new date()).gettime();

now have timer checks if key still pressed. if so, like:

this._delay = (new date()).gettime() - this._starttick; 

and now, based on this._delay, i'd find 1 of previous values (1, 2, 4 or 8). how that?

nb: if value greater "5.0" result should 32.

nota: goal is, given elapsed time, find out value best. started way i've explained, if have solution, i'll take it!

it's easier operate on array on object:

var accarr = []; (time in acc) {     accarr.push({time: time, value: acc[time]}); } 

assuming have array, can do:

function getvalue(delay) {     var diffs = accarr.map(function (e) { return math.abs(e.time - delay); });     return accarr[diffs.indexof(math.min.apply(null, diffs))].value; } 

edit:

well, didn't mention performance-critical function. in case, recommend picking granularity (e.g. 0.05, multiplier delay 20) , pre-calculating values 0 max_delay:

var multiplier = 20,     granularity = 1 / multiplier;  var delayvalues = (function () {     var result = [];     (var delay = 0; delay <= max_delay; delay += granularity) {         result.push(getvalue(delay));     }     return result; })(); 

during animation, fetching value simple lookup in relatively small table:

function getvaluefast(delay) {     return (delayvalues[math.round(delay * multiplier)] ||              delayvalues[delayvalues.length - 1]) } 

jsperf comparison between solution , simple if statements shows perform equally fast searching around middle value.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -