I have a JSON object with an array of “updates”, where each “update” consists of a timestamp and a message:
updates : {
{
timestamp : 1329505671,
text : 'test1'
},
{
timestamp : 1329505783,
text : 'test2'
}
}
Using jQuery, I parse these into DOM elements and insert them at the same level, in the order they were received. They are presorted based on my SQL query in the AJAX call.
Now, I have a recurring ajax call that checks for new updates. If an update is found, it needs to insert it into the DOM, in the appropriate position.
I cannot assume that these updates will always be the newest update in the list, so, I need a way to find which DOM update to insert the new update after.
I had planned on creating a Map<int, DOMUpdate> of sorts (updates[timestamp] = DOMUpdate in Javascript).
There are a couple flaws with this plan, though:
- I’d have to find/create a fast binary search algorithm for finding
which timestamp to put the update after. - I couldn’t have duplicate timestamps.
So my question is if anyone else has done something similar, and if so, how did you approach it? Please let me know if I’m being unclear in any way.
Just find the first element that has a timestamp that is greater than it and append it before that element. If none are found, it is the newest and should be appended at the start/end depending on the order you are posting them(newest first or last).
Obviously this is just a concept, you will need to modify it to fit your code/requirements.
Edit:
If you stored your data in an array of objects, and then added objects to that array as more were received, you could sort that array on the timestamp and then append the new objects based on the index after sorting. You would have to add a property to the newly received objects, and then remove that property as you loop through all of the objects and append only those that have that property.