No title Revision 303139353737 (Mon Aug 08 2011 at 04:59) - Diff Link to this snippet: https://friendpaste.com/22qa8u7nWWqFLrwCF6E7cT Embed: manni perldoc borland colorful default murphy trac fruity autumn bw emacs pastie friendly Show line numbers Wrap lines 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899/* comment */comment = { _id: "itsid" _rev : "", link_id: "id of item you comment", parent: "id of parent"n children: "comment children",}/* map function */function(doc) { if (doc.kind == "comment") { emit(doc.link_id, doc); }} /* reduce */function (key, values) { var idx_comments = {}; var comments = []; for (var i=0; i<values.length; i++) { if (values[i]) { idx_comments[values[i]['_id']] = values[i]; if (!values[i]['parent']) comments.push(values[i]); } } function iter_comments(lcomments) { for (var i=0; i<lcomments.length; i++) { var comment = lcomments[i] || []; var thread=[]; if (comment['children'] && comment['children'].length > 0) { for (var j=0; j<comment['children'].length; j++) { thread.push(idx_comments[comment['children'][j]]); } if (thread && thread.length >0) { comment['thread'] = iter_comments(thread); } else { comment['thread'] = null; } } lcomments[i] = comment } return lcomments; } tmp = iter_comments(comments); return tmp;}/* rereduce */function(key, values) { function cmp(a, b) { if (a['created'] > b['created']) return true; return false; } function swap(arr, i, j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } function partition(arr, start, end, pivot) { var pval = arr[pivot]; swap(arr, pivot, end--); while (start < end) { if (cmp(arr[start], pval) { swap(arr, start, pivot); pivot++; } } swap(arr, pivot, end+1); return pivot; } function qsort(arr, start, end) { if (start < end) { var pivot = partition(arr, start, end, start); qsort(arr, start, pivot); qsort(arr, pivot+1, end) } } function iter_comments(comments) { qsort(comments, 0, comments.length-1); for (var i=0; i<comments.length; i++) { comment = comments[i]; if (comment['thread'] and comment['thread']>1) comment['thread'] = iter_comments(comment['thread']); comments[i] = comment; } return comments; } return iter_comments(values);}