Skip to content

Instantly share code, notes, and snippets.

@garbados
Last active December 21, 2015 23:29
Show Gist options
  • Save garbados/6382861 to your computer and use it in GitHub Desktop.
Save garbados/6382861 to your computer and use it in GitHub Desktop.
Example map function with sample output and list function.
function(head, req){
var i,
x,
results = {},
headers = {},
csv = [];
while(x = getRow()){
(function(row){
var result = results[JSON.stringify(row.key)] || {};
for(i in row.value){
headers[i] = true;
result[i] = row.value[i];
}
for(i in row.key){
headers[i] = true;
result[i] = row.key[i];
}
results[JSON.stringify(row.key)] = result;
})(x);
}
headers = Object.keys(headers);
for(i in results){
csv.push(results[i]);
}
csv = csv.map(function(row){
var csv_row = [];
for(i in headers){
var header = headers[i];
csv_row.push(row[header]);
}
return csv_row;
});
csv.unshift(headers);
send(csv.map(function(row){
return row.join(',');
}).join('\n'));
}
1000 1001 1002 studyId subjectId eventId
female 22 10-Oct-2012 1 74850 SCR
female 22 10-Oct-2012 1 0 SCR
female 22 10-Oct-2012 1 1 SCR
female 22 10-Oct-2012 1 10 SCR
female 22 10-Oct-2012 1 100 SCR
female 22 10-Oct-2012 1 1000 SCR
female 22 10-Oct-2012 1 1001 SCR
female 22 10-Oct-2012 1 1002 SCR
female 22 10-Oct-2012 1 1003 SCR
female 22 10-Oct-2012 1 1004 SCR
female 22 10-Oct-2012 1 1005 SCR
female 22 10-Oct-2012 1 1006 SCR
female 22 10-Oct-2012 1 1007 SCR
female 22 10-Oct-2012 1 1008 SCR
female 22 10-Oct-2012 1 1009 SCR
female 22 10-Oct-2012 1 101 SCR
female 22 10-Oct-2012 1 1010 SCR
female 22 10-Oct-2012 1 1011 SCR
female 22 10-Oct-2012 1 1012 SCR
female 22 10-Oct-2012 1 1013 SCR
{
"total_rows": 10000,
"offset": 1,
"rows": [
{
"id": "8a41c8ae025a90c8d748aeb71746ef71",
"key": {
"studyId": 1,
"subjectId": "0",
"eventId": "SCR"
},
"value": {
"1000": "female",
"1001": " 22 ",
"1002": "10-Oct-2012"
}
}
]
}
function (doc) {
if (doc.type == "record" && doc.deleted !== true) {
var i,
keys = {},
values = {};
if (doc.studyId) {
keys.studyId = doc.studyId;
for (i in doc.mappingRules) {
var mappingRule = doc.mappingRules[i],
columnId = require('views/lib/module').test(doc, mappingRule.sourceColumn);
switch(mappingRule.columnType){
case "subject":
keys.subjectId = columnId;
break;
case "event":
keys.eventId = columnId;
break;
case "variable":
values[mappingRule.variableId] = columnId;
break;
}
}
emit(keys, values);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment