I've just started using Lazy.js, which is my first exposure to a "functional style" javascript library. I'm still utterly lost as to which of the hundred different functional javascript libraries to use, but so far I like Lazy.js, so I've used it to write a tag harvesting module for a blog engine project I'm working on. For anyone unfamiliar with Lazy.js (even moreso than I am) I'm under the impression its syntax is very similar to Underscore and Lodash.
getTagsWithCount: function(articles) { var tags = Lazy(articles).compact().pluck("attributes").pluck("tags").flatten().compact().sort().countBy() return tags // returns a Lazy.js Sequence }, // Formats a Sequence of tag objects into the specific kind of JSON array for spoonfeeding to fussy baby tag-cloud.js formatForTagCloud: function(tags) { var keysToJSON = tags.keys().map(function(x){return {"tagName": x, "count": tags.get(x)};}).toArray(); var json = JSON.stringify(keysToJSON); return json; }
Specific things I'm interested in/suspect I've done wrong:
- Is there a better way to dodge potential nulls in both the article array and in the tags of each articles than the double
compact()
? What's the performance impact ofcompact()
? If it's light, should I make a habit of using it everywhere as a general way of avoiding null/undefined values in arrays? - Is there a better way to do what I'm trying to do in formatForTagCloud? This function was purely to force my data into a format needed by a module I've actually ended up abandoning, but I'm presenting it here because writing it was a bit of a headache. Is there a different/better way of accessing both the key and the value of an ObjectLikeSequence? More to the point, I thought this would be a case where I could use either
merge()
orzip()
, but neither of those worked, leaving me with this approach which I'm concerned would be considered a bit crude. - I'm in the habit of creating variables then returning them, but I've seen other people write it the function so that the value is just returned without a variable being created first. Which is better? Are there performance benefits to be gained by doing the latter?
- Should I be putting newlines after some/all of my chained methods? Again, it's something I see, but I also sometimes find it a tiny bit confusing – but that's probably because I'm fairly new to the pattern.