DailyJS

DailyJS

The JavaScript blog.


Tagmodules
Featured

libraries functional modules reactive

most.js: Monadic Reactive Streams

Posted on .

Nick Ts. sent in most.js (GitHub: cujojs/most, License: MIT, npm: most), a reactive programming library designed for working with streams of values and events. You can use it with WebSocket, DOM events, and it should work with fantasy land and Promises/A+.

Let's say you've got an HTML fragment that you want to make dynamic. It should update in real-time based on user input. Here's a snippet:

<form>  
  <input class="x"> + <input class="y"> = <span class="result"></span>
</form>  

The goal is to make the form sum two numbers. Given a simple add function, and a function to cast the form's strings to numbers, a reactive most.js implementation could look like this:

var most = require('most');

var xInput = document.querySelector('input.x');  
var yInput = document.querySelector('input.y');  
var resultNode = document.querySelector('.result');

exports.main = function() {  
  // x represents the current value of xInput
  var x = most.fromEvent('input', xInput).map(toNumber);

  // y represents the current value of yInput
  var y = most.fromEvent('input', yInput).map(toNumber);

  // result is the live current value of adding x and y
  var result = most.combine(add, x, y);

  // Observe the result value by rendering it to the resultNode
  result.observe(renderResult);
};

function add(x, y) {  
  return x + y;
}

function toNumber(e) {  
  return Number(e.target.value);
}

function renderResult(result) {  
  resultNode.textContent = result;
}

The API is different to React and Knockout, but you should be able to follow it. There's a method called fromEvent that can map DOM events to JavaScript functions, then a method called combine that creates a new stream based on the streams from the two inputs. What's cool about this is you could further process the streams with to do things like throttling or tailing the results.

The people behind most.js have made sure it performs well, and there are some promising benchmarks. The library itself is from cujoJS, which is described as a toolkit for building web applications. The most.js readme has some functional and ES6 generators, so if you're interested in seeing what most.js looks like with generators then take a look there.

You can use most.js without worrying too much about what things like monads and functors are, but if you're interested in functional programming in JavaScript then you should try out Fantasy Land Specification.

Featured

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.

Featured

libraries console node apps modules npm iojs

Node Roundup: TJ Steps Down, Node and io.js Performance, Cloud Commander, Blessed

Posted on .

TJ Steps Down

Timothy J Fontaine has stepped down as the leader of the Node project:

Given the strength of its community, I'm confident that Node.js is heading in the right direction. With that said, it's time for me to step back.

The formation of the Node.js Foundation couldn't have happened at a better time in the life of Node.js. I believe this will be the tipping point that cements Node's place in technology. Soon, the foundation will be announcing its first meeting, initial membership, and future plans for Node.js.

The announcement includes details about Julien Gilli's work on the project, who is paid as a full-time developer on Node itself:

Julien has been responsible for the last few releases of Node.js -- both the v0.10 and v0.12 branches.

Thanks to him, we were able to ship v0.12.0 with all our tests passing and on all of our supported platforms. This was the first Node.js release ever to have that feature.

There's also another post on the Node blog by Scott Hammond that reiterates the move towards the Node.js Foundation:

Under the aegis of the Foundation, the Node.js project is entering the next phase of maturity and adopting a model in which there is no BD or project lead. Instead, the technical direction of the project will be established by a technical steering committee run with an open governance model.

That all sounds promising, except most of us just want a Node that has ES6 features without flags and continued updates to the V8 core. Naturally that brings me to io.js which just hit version 2.0.1. This release updates libuv and V8, and has fixes for async-wrap, documentation, and some of the internal C++ in the src/ folder. And you may also remember that the io.js 2.0.x branch has enabled lots of ES6 features without flags.

Node and io.js Performance

Nick Harley sent in Performance Showdown: Node.js vs. io.js v2.0.0:

A 14.8% speedup from Node to the latest version of io.js - certainly worthy of note. If you’re looking at one of the latest generation of JS backend frameworks, it certainly pays to give io.js a look as out-of-the-box you get some rather impressive perf improvements. When running a cluster of VMs using the Node stack, depending on scale, that speedup may result in several fewer boxes needed and correspondingly less infrastructure costs - all for free.

Cloud Commander

Coderaiser sent in Cloud Commander (GitHub: coderaiser/cloudcmd, License: MIT, npm: cloudcmd), a Node app that's been under active development since 2012. It's a file manager that reminded me of a web version of Midnight Commander, and it bundles CodeMirror and Ace so you can edit code with it quite comfortably.

It's built with Express and Socket.IO, and I was pleased to see they're on Express 4.x. The documentation the homepage includes details on how to deploy it with a non-root user for Linux/iptables or nginx.

The web app has a console interface as well, so you can type commands rather than using the web GUI.

Blessed and Blessed-Contrib

A colleague kept telling me how good Blessed-Contrib was, and I've only briefly mentioned Blessed on DailyJS before so I wanted to mention it. The attached gif illustrates why. Blessed is a curses-like library, but it has a very high-level API that I find much easier to understand than most terminal GUI libraries.

However, the magic really happens when you get blessed-contrib:

Blessed-Contrib

I've been waiting for something like this for years but never found a high-level scripting language library good enough to make my 1980s Unix console UI fantasies come true. Now I can finally bring to life my W.O.P.R version of our status dashboard!

Featured

libraries modules tabs localStorage client-side

The Local Storage Bridge

Posted on .

Doing something as simple as passing values between iframes and tabs is surprisingly awkward, and you'll end up trying anything to get it to work. Krasimir Tsonev has created a library called lsbridge (GitHub: krasimir/lsbridge, License: MIT, npm: lsbridge), or Local Storage Bridge. It allows you to send messages between tabs using Local Storage as a communication channel.

lsbridge

The API uses the .send and .subscribe methods to pass messages one way. You can also call lsbridge.isLSAvailable to check if the Local Storage API itself is available. Here's an example of the usage:

lsbridge.send('my-namespace', { message: 'Hello world!' });

lsbridge.subscribe('my-namespace', function(data) {  
  console.log(data); // prints: { message: 'Hello world!'}
});

console.log(lsbridge.isLSAvailable); // prints "true" or "false"  

Internally, lsbridge uses a setTimeout polling loop to set and remove items. The interval is 100 milliseconds, and there's a separate interval for item removal which is set to a second.

This is a pragmatic way to send data between tabs that doesn't require ugly hacks. For more context behind the library, see Krasimir's blog post Using Local Storage as a communication channel.

Featured

libraries modules npm angularjs state-machine

ngPromiseStatus, fsm-event

Posted on .

ngPromiseStatus

ngPromiseStatus (GitHub: BarakChamo/ng-promise-status, License: MIT, npm: ng-promise-status) by Barak Chamo is a collection of promise-aware Angular directives that make it easy to bind UI elements to the outcome of promises. This could be a button that takes an unspecified amount of time to run, that will eventually display success or failure.

You can also bind the promise values to alerts, and the author has provided Bootstrap samples that use Bootstrap's ubiquitous .alert message boxes.

fsm-event

fsm by Dominic Tarr is a very useful module for making finite state machines. I've used it with some success on a few Node projects. However, when I'm writing Node I prefer to deal with streams and events, rather than the methods in fsm's API. Yoshua Wuyts sent in fsm-event (GitHub: hyoshuawuyts/fsm-event, License: MIT, npm: fsm-event), a wrapper that uses EventEmitter.

To use it, create a new instance of fsm with the states you need, and then call m(state) to enter a given state. The corresponding listener will fire.

Why? Most state machines have overly complicated interfaces for managing state. The fsm state machine is simple but doesn't manage state for you, so I wrote a wrapper around it that manages state in an event-driven way. The initial use case was to manage complex, stateful UI elements but it can be used anywhere.

This would have actually helped with my specific use of fsm, where I ended up using it heavily alongside EventEmitter objects.