Reducer implementaion

It is just a question for educational purpose

If you want implement built in reducers (_count, _sum, _stats) in JavaScript , how you do it?

1 - Please show me how we can implement _count, _sum, _stats
2- Please show me how can I have a average reducer

Thanks a lot

I read document and see example here https://docs.couchbase.com/server/6.0/learn/views/views-writing-rewriting.html
I read https://docs.couchbase.com/server/6.0/learn/views/views-writing-rereduce.html too

I create reducer to calc average

function(key, values, rereduce) {
  var result = {total: 0, count: 0, average: 0};
  for(i=0; i < values.length; i++) {
    if(rereduce) {
        result.total = result.total + values[i].total;
        result.count = result.count + values[i].count;
        result.average=result.total/result.count;
    } else {
        result.total = sum(values);
        result.count = values.length;
        result.average=result.total/result.count;
    }
  }
  return(result);
}

But I cannot understand how incremental works , for instance how it handle deleting a document?

Can you explain as it explained in https://docs.couchbase.com/server/6.0/learn/views/views-writing-rereduce.html like

function('James', [ 13000,20000,5000 ]) {...}

function('James', [ 19000, function('James', [ 13000,20000,5000 ]) ]) { ... }

function('James', [ 19000, 38000 ]) { ... }

Please reply … …

@matthew.groves @siri can you help me? Please

Up again …

Reply please , I want to know how delete a record runs reducer function?
Show me an example like

function('James', [ 13000,20000,5000 ]) {...}

function('James', [ 19000, function('James', [ 13000,20000,5000 ]) ]) { ... }

function('James', [ 19000, 38000 ]) { ... }