Skip to content

Commit

Permalink
(#37 / daleharvey/pouchdb#1264) closures in temp views
Browse files Browse the repository at this point in the history
  • Loading branch information
calvinmetcalf authored and nolanlawson committed Feb 2, 2014
1 parent c6811d5 commit 82c6099
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
18 changes: 13 additions & 5 deletions index.js
Expand Up @@ -156,7 +156,7 @@ function MapReduce(db) {

function viewQuery(fun, options) {
/*jshint evil: true */

var origMap;
if (!options.skip) {
options.skip = 0;
}
Expand Down Expand Up @@ -213,10 +213,18 @@ function MapReduce(db) {
}
results.push(viewRow);
}
// ugly way to make sure references to 'emit' in map/reduce bind to the
// above emit

eval('fun.map = ' + fun.map.toString() + ';');
if (typeof fun.map === "function" && fun.map.length === 2) {
//save a reference to it
origMap = fun.map;
fun.map = function (doc) {
//call it with the emit as the second argument
return origMap(doc, emit);
};
} else {
// ugly way to make sure references to 'emit' in map/reduce bind to the
// above emit
eval('fun.map = ' + fun.map.toString() + ';');
}
if (fun.reduce) {
if (builtInReduce[fun.reduce]) {
fun.reduce = builtInReduce[fun.reduce];
Expand Down
33 changes: 31 additions & 2 deletions test/test.js
Expand Up @@ -58,8 +58,37 @@ function tests(dbName) {
});
});
});

it("Test passing just a function", function () {
if (dbName.slice(0, 4) !== "http") {
it("with a closure", function () {
return pouchPromise(dbName).then(function (db) {
var bulk = denodify(db.bulkDocs);
return bulk({docs: [
{foo: 'bar'},
{ _id: 'volatile', foo: 'baz' }
]}).then(function () {
var queryFun = (function (test) {
return function (doc, emit) {
if (doc._id === test) {
emit(doc.foo);
}
};
}('volatile'));
return db.query(queryFun, {reduce: false});
});
}).should.become({
total_rows: 1,
offset: 0,
rows: [
{
id: 'volatile',
key: 'baz',
value: undefined
}
]
});
});
}
it("Test passing just a function", function (done) {
return pouchPromise(dbName).then(function (db) {
var bulk = denodify(db.bulkDocs);
var get = denodify(db.get);
Expand Down

0 comments on commit 82c6099

Please sign in to comment.