I am trying to assess whether my CLJS function declaration is idiomatic. Here is my attempt to convert a JS function into its corresponding CLJS function. (You can ignore the actual content of the function).
JavaScript function:
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:
(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")))))))
1 Answer 1
Seems fine to me. As @cfrick points out in the comments, you could make the code more terse in some ways (e.g. using an anonymous function, which is idiomatic where its a single-use and relatively simple). 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. 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.
filterand for something simple as the .endsWith check just#(.endsWith % ".dec"). also the cljs version ignores theerrcase. and at least in the browserprintlnbehaves different thanconsole.log.