Mercurial > browser-couch
changeset 45:3a34b9ed3a36
Added a simple findRow() method to the MapView class that finds the first row of a given key using binary search.
author | Atul Varma <varmaa@toolness.com> |
---|---|
date | Tue, 14 Apr 2009 11:50:46 -0700 |
parents | fec67509fc3d |
children | 6da7638d056f |
files | browser-couch.js tests.js |
diffstat | 2 files changed, 34 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- a/browser-couch.js Tue Apr 14 11:25:34 2009 -0700 +++ b/browser-couch.js Tue Apr 14 11:50:46 2009 -0700 @@ -413,13 +413,14 @@ _MapView: function BC__MapView(mapDict) { var rows = []; - + var keyRows = []; this.rows = rows; var mapKeys = BrowserCouch._makeMapKeys(mapDict); for (var i = 0; i < mapKeys.length; i++) { var key = mapKeys[i]; var item = mapDict[key]; + keyRows.push({key: key, pos: rows.length}); for (var j = 0; j < item.keys.length; j++) { var id = item.keys[j]; var value = item.values[j]; @@ -428,5 +429,22 @@ value: value}); } } + + function findRow(key, keyRows) { + if (keyRows.length > 1) { + var midpoint = Math.floor(keyRows.length / 2); + var keyRow = keyRows[midpoint]; + if (key < keyRow.key) + return findRow(key, keyRows.slice(0, midpoint)); + if (key > keyRow.key) + return findRow(key, keyRows.slice(midpoint)); + return keyRow.pos; + } else + return keyRows[0].pos; + } + + this.findRow = function MV_findRow(key) { + return findRow(key, keyRows); + }; } };
--- a/tests.js Tue Apr 14 11:25:34 2009 -0700 +++ b/tests.js Tue Apr 14 11:50:46 2009 -0700 @@ -111,6 +111,21 @@ }}); }); }, + testViewMapFindRow_async: function(self) { + var map = this._mapWordFrequencies; + this._setupTestDb( + function(db) { + db.view( + {map: map, + finished: function(view) { + self.assertEqual(view.findRow("dogen"), 0); + self.assertEqual(view.findRow("dude"), 1); + self.assertEqual(view.findRow("hello"), 2); + self.assertEqual(view.findRow("there"), 4); + self.done(); + }}); + }); + }, testViewProgress_async: function(self) { var map = this._mapWordFrequencies; var reduce = this._reduceWordFrequencies;