您是否在提交之前清理了map / reduce函数?怎么样? [英] Do you clean your map/reduce functions before submission? How?

查看:66
本文介绍了您是否在提交之前清理了map / reduce函数?怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ouchdb中,可以用Javascript定义map和reduce函数,然后通过HTTP POST将其提交到服务器以定义视图。

In couchdb, one can define map and reduce functions in Javascript, and submit them via HTTP POST to the server to define views. Cool.

应用程序指定了各个函数的字符串表示形式。

Apps specify a string representation of the respective functions.

我正在构建一个可连接的JS应用程序使用文本编辑器emacs进入沙发数据库。这使我可以定义map和reduce函数,例如:

I am building a JS app that connects to couchdb, using emacs, a text editor. This lets me define map and reduce functions like this:

var byname = function(doc) { 
   emit(doc.name,null);
};

这给了我emacs语法突出显示,jslint检查等等。

This gives me emacs syntax highlighting, jslint checks, and so on.

在运行时,通过执行以下操作,我可以获取一组定义为这样的视图函数中每个视图的字符串表示形式,以将其发送到CouchDB:

At runtime, I can get the string representation of each one of a set of view functions defined like that, to send it to CouchDB, by doing this:

doc = { views: { empty:   { map:stringRep(empty) },
                 byname:  { map:stringRep(byname) },
                 invalid: { map:stringRep(invalid) }}};

// PUT that doc to couchdb here, to define the design_doc . 

但是字符串表示形式包括换行符,回车符等。

But the string representations include newlines, carriage returns, and so on.

我可以使用正则表达式替换来过滤掉它们,这适用于简单的情况。
但是函数中还有更复杂的带注释行的情况。例如:

I could filter those out with a regex replacement, which works for the simple case. But there is also the more complex case of commented lines in the function. For example:

var byname = function(doc) { 
   // a comment here
   emit(doc.name,null);
};

在这种情况下,stringRep将包含注释,但是如果我消除了换行符和伪空白,则注释保持。我也可以替换那些,但是可能还有其他问题(不确定)。

In this case the stringRep will include the comment but if I eliminate the newlines and dummy whitespace, the comments remain. I could replace those too, but there may be other problems (not sure).

人们是否有一种通常的或推荐的方式将人们的JavaScript函数清理后再发送到沙发上?

推荐答案

我最终使用的是:

CouchDB.stringRep = function(fn) {
    return fn.toString()
        .replace(/[\s\t]*\/\/.*$/gm, '') // comments
        .replace(/\n */gm, ' ')
        .replace(/\r */gm, ' ')
        .replace(/\{ +/gm, '{')
        .replace(/ +\}/gm, '}');
};

然后我用这种HTTP消息上传以这种方式序列化的函数:

And then I upload the functions serialized this way, with this kind of HTTP message:

PUT https://foo.cloudant.com/fop/_design/baseViews HTTP/1.1
Accept: text/plain,application/json
Accept-Language: en-us
User-Agent: Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)
Content-Length: ...
Host: foo.cloudant.com

{"views":{"empty":{"map":"function(doc) {if ( ! doc.observation || doc.observation === '') {emit(doc.id, 1);}}"},...}} 

这篇关于您是否在提交之前清理了map / reduce函数?怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆