Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>An immediate solution to this would be to store data in an array and use the object to simply store the index in the array at which an object exists.</p> <pre><code>var db = { data: [1, 2, 3], index: { a: 0, b: 1, c: 2 } }; function next(db, key) { var next = db.index[key] + 1; if (next &gt;= db.data.length) { return null; } return db.data[next]; } function prev(db, key) { var next = db.index[key] - 1; if (next &lt; 0) { return null; } return db.data[next]; } function add(db, key, value) { db.index[key] = db.data.push(value) - 1; } function remove(db, key) { var index = db.index[key], x, temp; if (index !== undefined) { delete db.index[key]; db.data.splice(index, 1); // Update indices of any elements after the removed element for (x in db.index) { temp = db.index[x]; if (temp &gt; index) { db.index[x] = temp - 1; } } } } </code></pre> <p>The basic idea is to use an ordered structure, in this case the array, to hold the data in a sequential manner. In this case, next and prev are both constant time, add is amortized constant time, and delete is O(N).</p> <p>The ordering of keys isn't guaranteed by the ECMA standard, so <code>for/in</code> doesn't need to be in the order keys were added (though in practice, that does tend to be the common implementation). In this solution, I use an array to explicitly keep track of insert order.</p> <p>Edit: I overlooked a deletion issue earlier with splice. The index would become incorrect for all values after the spliced value for a remove. The fix doesn't impact the running time complexity of the operation. A faster version with fewer removes could let the array become sparse and instead of splicing, simply set the index to null to free any reference stored there. This would lower the remove operation to O(1).</p> <pre><code>function remove(db, key) { var index = db.index[key]; if (index !== undefined) { delete db.index[key]; db.data[index] = null; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload