changeset 1:972d973433c7

Documents is now an array, and an index mapping document IDs to their position in the array is maintained.
author Atul Varma <varmaa@toolness.com>
date Thu, 09 Apr 2009 17:20:10 -0700
parents 3c23e383cd32
children 3997e13ca428
files browser-couch.js
diffstat 1 files changed, 19 insertions(+), 9 deletions(-) [+]
line wrap: on
line diff
--- a/browser-couch.js	Thu Apr 09 16:17:58 2009 -0700
+++ b/browser-couch.js	Thu Apr 09 17:20:10 2009 -0700
@@ -1,12 +1,24 @@
 var BrowserCouch = {
   get: function BC_get(name, cb) {
-    cb(new this._DB(name, new Object()));
+    cb(new this._DB(name, []));
   },
 
   _DB: function BC__DB(name, documents) {
+    var docIdIndex = {};
+
+    function putSingleDocument(doc) {
+      if (doc.id in docIdIndex)
+        documents[docIdIndex[doc.id]] = doc;
+      else
+        docIdIndex[doc.id] = documents.push(doc);
+    }
+
+    for (var i = 0; i < documents.length; i++)
+      putSingleDocument(documents[i]);
+
     this.get = function DB_get(id, cb) {
-      if (documents[id])
-        cb(documents[id]);
+      if (id in docIdIndex)
+        cb(documents[docIdIndex[id]]);
       else
         cb(null);
     };
@@ -14,9 +26,9 @@
     this.put = function DB_put(document, cb) {
       if (document.constructor.name == "Array") {
         for (var i = 0; i < document.length; i++)
-          documents[document[i].id] = document[i];
+          putSingleDocument(document[i]);
       } else
-        documents[document.id] = document;
+        putSingleDocument(document);
       cb();
     };
 
@@ -38,10 +50,8 @@
         mapResult[key].push(value);
       }
 
-      for (id in documents) {
-        var document = documents[id];
-        map(document, emit);
-      }
+      for (var i = 0; i < documents.length; i++)
+        map(documents[i], emit);
 
       if (reduce) {
         var keys = [];