1

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")))))))
George
  • 6,927
  • 4
  • 34
  • 67
  • 2
    Might be a better fit for the code review site - since this code works as expected, right? – cfrick Jan 06 '16 at 07:42
  • @cfrick "You can ignore the actual content of the function" sounds like it's not really a fit for Code Review. [codereview.se] is all about working code that does things, where it's relevant what happens. as such this is probably not a good fit for the site :/ – Vogel612 Jan 06 '16 at 08:14
  • 2
    well, then here are my 2ct: i'd use clojurescripts own `filter` and for something simple as the .endsWith check just `#(.endsWith % ".dec")`. also the cljs version ignores the `err` case. and at least in the browser `println` behaves different than `console.log`. – cfrick Jan 06 '16 at 08:55

1 Answers1

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.

leeor
  • 17,041
  • 6
  • 34
  • 60
  • Ok. Do you have any thoughts on my code indentation? It feels awkward to have the cljs function I wrote go so far off the page to the right. In that respect, is there anything I'm doing which fails to be idiomatic? – George Jan 06 '16 at 17:17
  • in terms of style guidelines (e.g. indentation) I would take a look at https://github.com/bbatsov/clojure-style-guide. I think its the de-facto standard AFAIK. – leeor Jan 06 '16 at 17:28