The JavaScript blog.


lazy lisp modules clojure algorithms

Lazy Arrays

Posted on .

Oliver Caldwell has been working on a module that lets you use lazy arrays (GitHub: Wolfy87/lazy-array, License: The Unlicense, npm: lazy-array) in JavaScript. If you've ever used Clojure for any amount of time you'll find you start actually thinking in lazy sequences, and start wanting to use them on other platforms.

Clojure's lazy sequences are sequences of values that you can query, slice, and compose. They're generated algorithmically but don't haven't to exist entirely in memory. A good example of this is the Fibonacci sequence. With Oliver's module you can define and manipulate the Fibonacci sequence like this:

var larr = require('lazy-array');

function fib(a, b) {  
  return larr.create(function() {
    return larr.cons(a, fib(b, a + b));

var f = fib(1, 1);  
larr.nth(f, 49); // 12586269025  

In this example, the larr.create method defines a sequence using larr.cons, which is a "core sequence" function. The methods provided by Lazy Array are based on Clojure's lazy sequence methods, so you get the following:

  • first: Get the first item
  • rest: Get the tail of the array
  • cons: Constructs a new array by prepending the item on the list
  • take: Returns a lazy array which is limited to the given length
  • drop: Returns a lazy array which drops the first n results
  • nth: Fetches the nth result

There are more methods -- if you want to see the rest look at the JSDoc comments in lazy-array.js.

Lazy sequences are not magic: you can easily make Clojure blow up:

(defn fib [a b] (lazy-seq (cons a (fib b (+ a b)))))

(take 5 (fib 1 1))
; (1 1 2 3 5)

(take 2000 (fib 1 1))

; ArithmeticException integer overflow  clojure.lang.Numbers.throwIntOverflow (Numbers.java:1424)

But the point isn't that they're a way of handling huge piles of data, it's more a programming primitive that makes generative algorithms easier to reason about. What I really like about Oliver's work is he links it to UI development:

We JavaScript frontend wranglers deal with events, networking and state all day long, so building this had me wondering if I could apply laziness to the UI domain. The more I thought about this concept and talked with colleagues about it I realised that I’m essentially heading towards functional reactive programming, with bacon.js as a JavaScript example.

The UI example Oliver uses is based on an infinite lazy array of all possible times using a given start date and step timestamp. This might be a concise way of representing a reactive calendar widget.

If you're interested in lazy sequences and want to read more about Clojure, I found Lazy Sequences in Clojure useful when fact checking this article.


tutorials JSON clojure node ES6 generators

Recreating core.async with ES6 Generators, JSON Mask

Posted on .

Recreating core.async with ES6 Generators

Recreating core.async with ES6 Generators is a post by Andrey Popp inspired by Clojure's core.async. He uses Browserify with a transpiler module that allows ES6 generators to be used in browsers:

function *listen(el, evType) {  
  while (true)
    yield function(cb) {
      var fire = function(ev) {
        el.removeEventListener(evType, fire);
        cb(null, ev);
      el.addEventListener(evType, fire);

The tutorial goes on to use JSONP to fetch data from the Wikipedia API. The full source is available as a gist: andreypopp / index.html.


JSON Mask (GitHub: nemtsov / json-mask, License: MIT, npm: json-mask) by Yuriy Nemtsov is a module that provides a DSL for filtering JSON. It works in browsers, includes unit tests, and there's also Express middleware that can help you filter responses in your Express applications.

One use-case is when you have an HTTP service that returns {"name": "mary", "age": 25} (for example), and you have two clients: (1) that needs all of that information, and (2) that just needs the name.

Now, if the server uses JSON Mask, it would accept a ?fields= query-string. The (2)nd client would then add the following query-string to the request: ?fields=name; after which the server would respond with {"name": "mary"}, and filter out the rest of the information.

This saves bandwidth and improves performance; especially on large objects.

Although trivial in the simplest cases, the task of filtering objects becomes a difficult one quickly. This is why JSON Mask is actually a tiny (and highly optimized) language that is loosely based on XPath, and has support for filtering parts of objects, arrays, wild-card filtering and combinations of the three. So, here's a less trivial example and usage (note how p/a/b is filtered out):


clojure templating node modules mongodb

Node Roundup: Mongovi, hoquet

Posted on .


I've been working on a project that uses MongoDB, and one of the problems I have is with Mongo's REPL. For one thing, I keep hitting CTRL-C because I expect it to cancel the current line rather than exit the whole REPL, but a bigger problem for me is they've switched to linenoise. I'm used to Vim's shortcuts, which readline can use. When dealing with programs with non-readline REPLs, I often invoke rlwrap (or write an alias to use rlwrap), but when it comes to Mongo a better solution might be Tim Kuijsten's Mongovi.

Mongovi (GitHub: timkuijsten / node-mongovi, License: MIT, npm: mongovi) is a REPL for MongoDB with Vi keys. It uses readline-vim and node-mongodb-native, so it isn't a wrapper around the command-line mongo tool but instead a reimplementation in Node.

Several high-level commands work: show dbs lists databases, use db switches to a different database, and the usual commands like c.collectionName.find, update, and insert work. The author has included Mocha tests, and documentation can be found in the readme.


I had a brief love affair with Clojure. It was a romance that lasted a few months, but work got in the way and we had to break up. However, thanks to Tom Brennan I can relive those days with hoquet (GitHub: tjb1982 / hoquet, License: MIT, npm: hoquet). This is a templating library based on Clojure's Hiccup. It uses a structured language based on arrays for generating HTML:

var http = require('http'),  
    h = require('hoquet');

function layout(c) {  
  var out =
      ['title', c.title],
     ['body', {'ng-app':'MyApp'}, c.body]];

  return out;

var index = layout({  
  title: 'My Page',
  body: ['div', {'ng-view':''},
         ['h1', 'Hello world']],
  head: [['meta', {'name':'description',

http.createServer(function(q,s) {  
  s.writeHead(200, {'Content-Type': 'text/html'});
  s.end( h.doc('html5', index) );

Tom also notes that hoquet can be used in browsers, because the underlying implementation is plain ol' JavaScript:

You create your own functions/literals to pass in whatever you want and call render, which stringifies it. You can also render inner portions at any time and insert them as Strings so you don't have to worry about when render is called.


lisp javascript clojure

Scriptjure and JavaScript/Scheme

Posted on .

Scriptjure is an interesting project for those of you who like Clojure. It
generates JavaScript like this:

(js (alert "hello world")) 
=> "alert(\"hello world\")"

(js (foo x y)) 
=> "foo(x, y)"

(js (if (== foo 3) (foo x) (bar y)))
=> "if ( (foo == 3) ) {
   else {

Other related projects that are worth looking at are Lisp in

This reminded me of The Little
which was an
interesting essay by Douglas Crockford, based on The Little LISPer. If
you've heard people saying Scheme and JavaScript are related but aren't
sure what this means, it's worth reading it. Google Books has a viewable
version of The Littler Schemer so you can follow