简体   繁体   English

我的这个JS函数的ClojureScript翻译是惯用的吗?

[英]Is my ClojureScript translation of this JS function idiomatic?

I am trying to assess whether my CLJS function declaration is idiomatic. 我正在尝试评估我的CLJS函数声明是否惯用。 Here is my attempt to convert a JS function into its corresponding CLJS function. 这是我尝试将JS函数转换为其相应的CLJS函数的尝试。 (You can ignore the actual content of the function). (您可以忽略该函数的实际内容)。

JavaScript function: JavaScript函数:

var dir = require('node-dir');

function jsFunc(path) {
    dir.files(path, function(err, files) {
        if (err) throw err;
        files = files.filter(function (file) {
           return file.endsWith('.dec');
        });

        console.log(files);
    });
}

My translation into ClojureScript: 我翻译成ClojureScript:

(defn cljs-func [input-path]
  (let [dir (node/require "node-dir")]
    (.files dir input-path (fn [err files] 
                               (println (.filter files (fn [file] (.endsWith file ".dec")))))))

Seems fine to me. 对我来说似乎很好。 As @cfrick points out in the comments, you could make the code more terse in some ways (eg using an anonymous function, which is idiomatic where its a single-use and relatively simple). 正如@cfrick在注释中指出的那样,您可以通过某些方式使代码更简洁(例如,使用匿名函数,该函数是惯用用法,它是一次性的,相对简单)。 Once you start having multiple arguments, I think it starts to make more sense to have an inline function declaration for readability's sake. 一旦开始具有多个参数,为便于阅读起见,内联函数声明就变得更加有意义。

I would also second @cfrick's advice on preferring clojurescript's version of filter and any other function calls of this sort. 我还要赞同@cfrick的建议,建议使用clojurescript的filter版本和此类其他函数调用。 I think the less you directly depend on the host environment, the more portable your code becomes. 我认为您对主机环境的直接依赖越少,代码的可移植性就越高。 Certainly a trend that many clojure projects are going in these days with the introduction of reader conditionals in clojure 1.7. 当然,随着clojure 1.7中引入读者条件语句,当今许多clojure项目正在发展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM