javascript - ceilingEntry and floorEntry

637 views Asked by At

I have an object with double keys and object values, e.g.:

var animation = {
    0.0: position1,
    0.1: position2,
    0.4: position3,
    ...
}

I would like to know the ceiling and the floor key for a given value. e.g.:

ceilingKey(animation, 0.3) //should return 0.1
floorKey(animation, 0.3) //should return 0.4

I am open to any solution (e.g. the doubles don't necessary have to be object keys, they can even be a separate array).

The only solution I can think of is to iterate through the doubles and return when reached the celing/floor key (or to do a binary search if the doubles are in a separate array). Is there any more elegant solution?

1

There are 1 answers

0
T.J. Crowder On BEST ANSWER

The only solution I can think of is to iterate through the doubles and return when reached the celing/floor key (or to do a binary search if the doubles are in a separate array). Is there any more elegant solution?

I don't think so, no. To do the binary search, of course, you'll have to start with Object.keys to get an array of the property names and then sort it, since of course objects are inherently unordered. In other words, although you've written your object with the property names in ascending order, the JavaScript engine is under no obligation to visit those properties in that order either via for-in or Object.keys or any other iteration method. Many JavaScript engines visit properties in the order they're added to the object, but that is undefined behavior you won't want to rely on.


Side note: You said "doubles" a few times in your question, I believe referring to the property names. Beware that although you've written them as numbers (which is perfectly valid), the property names end up being strings, not numbers, because in ES5 and earlier property names are always strings (in ES6 we'll have both strings and Symbol objects):

var name = Object.keys({0.1:"foo"})[0];
snippet.log("name = " + name);
snippet.log("type = " + typeof name);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

So you'll want to allow for that when doing your comparisons.