Web Worker Contest, Steady.js, Jasmine Integration Tests

13 Jun 2014 | By Alex Young | Comments | Tags jasmine testing webworker ui

Web Worker Contest

The Web Worker Contest, sent in by Stefan Trenkel, is a JavaScript game where two programs compete to conquer a two-dimensional space using simple movement commands.

On a playing area of 100 x 100 square fields two JavaScript programs compete against each other. From a randomly allotted starting point they must conquer as many fields as possible. The winner is who occupies most fields at the end. A move is to conquer from the current field either the upper, lower, right or left adjacent field. The new field can be occupied only if it was not previously occupied by the opponent’s program. If a move is possible (the new field is free) the current position changes to the desired field. If a move is not possible (the field is occupied by the opponent or you want to leave the playing area), you stay on the current position. Fields that one has previously occupied can be used again (but do not count double). The programs do not have any information about the playing area.

The contest is based on the Web Worker API:

Your own Web Worker is simply a local JavaScript file with appropriate code. In this case your own Web Worker is not uploaded to the server. This option is primarily for testing and optimizing your own Web Worker. If you want to participate in the WWC you have to upload your Worker on the Upload page.

You can view running games and read more about the concept in the guide.

Steady.js

Steady.js (GitHub: lafikl / steady.js, License: MIT) by Khalid Lafi is a library for elegantly responding to onscroll events. With Steady.js, the onscroll handler collects data, then offloads the work to requestAnimationFrame. It throttles events, and works like @media-query.

Steady.js is based around “trackers”: these provide the logic that the data collector uses. An example of a built-in tracker is scrollTop which indicates how far a scrollable element has moved from the top.

Basic usage looks like this:

var s = new Steady({
  conditions: {
    width: 400,
    scrollX: 0,
    max-bottom: 200
  },
  throttle: 100,
  handler: fn
});

s.addCondition('scrollX', 0);

The documentation has an example of a custom tracker that you can extend with your own behaviour.

Jasmine Integration Tests

jasmine-integration by Jordi Noguera is an integration testing extension for Jasmine. It allows you to run tests in browsers by using an iframe, or in headless mode using PhantomJS.

The documentation shows how to use it with Grunt, so you can execute your tests against a browser with grunt jasmine:server, or in headless mode using grunt jasmine:server:ci.

Jordi has written a sample app with tests called node-todo which demonstrates how the same specs can be used for browser testing and headless tests on the command-line.

Why Ramda?, Two-Way Data Binding Review

12 Jun 2014 | By Alex Young | Comments | Tags ui data-binding functional mvvm

Why Ramda?

Scott Sauyet sent in Why Ramda?, a post that attempts to explain the Ramda library:

To those not used to functional programming, Ramda seems to serve no purpose whatsoever. Most of its major capabilities are already covered by libraries like Underscore and LoDash.

These folks are right. If you want to keep coding with the same imperative and object-oriented styles you’ve been using, Ramda does not have much to offer you.

However, it does offer a different style of coding, a style that’s taken for granted in purely functional programming languages: Ramda makes it simple for you to build complex logic through functional composition. Note that any library with a compose function will allow you do functional composition; the real point here is: “makes it simple”.

The article builds on the functional composition idea and leads up to the kind of data-focused programming that Ramda makes possible.

Two-Way Data Binding Review

Two-Way Data Binding by Nikita Vasilyev is a review of two-way data binding in Backbone, React, Angular, Meteor and plain JavaScript.

It highlights an issue that some libraries might have if they change fields at the wrong time:

The problem is that data flows from an input field to a model, and then back to the same input field, overriding the current value even if it’s exactly the same.

React.js doesn’t have Backbone’s problem with moving the cursor position. Its virtual DOM, a layer between the actual DOM and React’s state, prevents React from unnecessary DOM changes.

There’s also an informative comment by Leo Horie about the effort required to learn each framework:

Something that strikes me about the framework versions is the amount of framework-specific knowledge required to get these examples working. It’s one thing to say “here’s a version in framework X”, and it’s quite another to actually write the code (from the standpoint of someone who’s still considering framework options and who is not familiar with the lingo and caveats for any of them.)

Node Roundup: npm's New Web Framework, Notes from the Road, TJ Fontaine Interview

11 Jun 2014 | By Alex Young | Comments | Tags node modules npm interviews

npm’s New Web Framework

In Nearing Practical Maintainability on the official npm blog, there’s a discussion about the decision to use hapi.js for npm’s new site:

Both Hapi and Express rate extremely well against our juding criteria. To choose between the two, it pretty much came down to the framework architecture: Hapi’s plugin system means that we can isolate different facets and services of the application in ways that would allow for microservices in the future. Express, on the other hand, requires a bit more configuration to get the same functionality (it’s certainly capable!).

The current npm-www has a lot of dependencies that you might have seen before: browserify, uglifyjs, moment, ejs, and nodemailer are all popular modules. I think using something like hapi.js or Express makes sense, even if it just gives the project some architectural hints.

While, yes, we could use barebones Node.js and roll our own framework, we want to avoid the same “special snowflake” situation that we’re currently in. Plus, by using a framework, we can focus more on pushing out the features our community wants and needs, instead of debugging some weird nook and/or cranny that someone forgot about.

Notes from the Road

Notes from the Road is a post on Node’s official blog by TJ Fontaine about the Node on the Road events:

These Node on the Road events are successful because of the incredible support from the community and the existing meetup organizations in their respective cities. But the biggest advantage is that the project gets to solicit feedback directly from our users about what is and isn’t working for them in Node.js, what modules they’re using, and where they need Node to do better.

From these experiences TJ has written up some notes about Node’s release schedule, future documentation improvements, and the path to becoming a Node contributor:

In an effort to make it easier for users to contribute to Node.js the project has decided to lift the requirement of signing the CLA before contributions are eligible for integration. Having to sign the CLA could at times be a stumbling block for a contribution. It could involve a long conversation with your legal department to ultimately contribute typo corrections.

TJ Fontaine Interview

Meanwhile, the Node hosting company Modulus has interviewed TJ Fontaine, where some of these points are reiterated:

If you’re looking for ways to contribute to Node itself, the website will be soon be going through an overhaul to improve our documentation. We’re going to be adding a lot more documentation, cleaning up what we already have, as well as designing the pieces to help internationalize the site. Node’s community is globally diverse, we should be working to enable Node users everywhere they are.

Node Hardware Hacking with Tessel

10 Jun 2014 | By Alex Young | Comments | Tags node hardware
Node-compatible hardware.

Imagine being able to run npm install gprs to add GPRS tracking support to a hardware project… Well, now you can with Tessel!

The idea behind hardware platforms like Tessel is to make it easier for software developers to interface with hardware. This is ideal if you’ve ever thought it would be nice to hook up a movement sensor to a camera to take a photo whenever your dog or cat moves.

Microcontrollers are chips that contain a processor, memory, and I/O. You can hook them up to sensors for input, and things like servos and speakers for output. Unfortunately microcontrollers have limitations – once you start adding the amount of RAM and processing power required for a high-level language like JavaScript then the costs add up. Also, while they can be programmed, most of them aren’t trivial to program – some have to be flashed with special hardware.

This is why Arduino was such a big deal: it made it easier for programmers and non-technical tinkerers to upload code to a microcontroller using a computer and USB cable.

Tessel and Espruino have iterated on Arduino by using slightly more powerful hardware to allow JavaScript to run. Espruino’s strength is it uses a specialised version of JavaScript that means it can use cheaper, low-powered hardware.

On the other hand, Tessel has built-in Wi-Fi and an ARM Cortex-M3 microcontroller. Because it’s so powerful, it can run thousands of standard Node modules straight from npm. And even better, Tessel has a wide selection of hardware modules, including:

  • Accelerometer
  • Audio (MP3/AAC/WMA/MIDI/FLAC/Ogg Vorbis)
  • Bluetooth LE
  • Camera
  • MicroSD
  • Relay (for controlling higher-powered devices)
  • Servo

Naturally all of these toys come at a price: Tessel with a single module costs $99. You can also buy Tessel with all available modules for $599.

I have an Espruino, but I don’t have a Tessel yet. I like the idea of using npm install with Tessel, but Espruino is already easy to connect to sensors and other hardware, particularly for those with Arduino experience.

My recommendation is to try Tessel if you’re perplexed by hardware but good at Node, and have some free time and cash.

jsEq, Angular-breadcrumb

09 Jun 2014 | By Alex Young | Comments | Tags angularjs equality

jsEq

jsEq (GitHub: loveencounterflow / jseq, License: ISC) is a deep equality test suite:

There are a couple of related, recurrent and, well, relatively ‘deep’ problems that vex many people who program in JavaScript on a daily base, and those are sane (deep) equality testing, sane deep copying, and sane type checking.

It highlights how much variance there is between different equality implementations, including lodash, Underscore, Node’s assert.deepEqual, and more.

The project uses dependencies from npm, so even though it uses lots of dependencies it’s easy to install and run the tests.

The readme has a list of axioms that are used to design the tests. So far, Underscore and lodash seem to be winning:

I sorted the results, and seeing that underscore got the highscore (pun intended), it surprised me to see that it insisted on treating +0 and -0 as not equal. Ultimately, this led to the discovery of the second Axiom, and with that in my hands, it became clear that underscore got this one right and my test case got it wrong: Since there are known programs that behave differently with positive and negative zero, these two values must not be considered equal.

The output of the test suite looks incredibly cool – you can easily see the output of a huge amount of tests. There’s a glorious console screenshot in the readme.

Angular-breadcrumb

Angular-breadcrumb (GitHub: ncuillery / angular-breadcrumb, License: MIT) by Nicolas Cuillery is a module for generating breadcrumb navigation. You can use the ncy-breadcrumb directive to apply it.

It’s based on the AngularUI Router, and Nicolas has been writing pretty solid documentation in the Angular-breadcrumb wiki.

MotorCortex.js, Testing AngularJS with Jasmine

06 Jun 2014 | By Alex Young | Comments | Tags animation jasmine testing angularjs

MotorCortex.js

Think of dancer dancing or a human just walking the street. It is extremely unnatural to think that each part of the body acts independently. A centralized mechanism controls all parts in order to produce a smooth, elastic and natural movement. The “motor cortex”, is the specific part of the brain that does exactly this job.

The idea of declarative templates seems to be spilling into the world of client-side animation. MotorCortex.js (GitHub: andreas-trad / motorcortexjs, License: WTFPL) by Andreas Trantidi is a new library that builds on Velocity.js to provide an animation API that’s based on CSS syntax.

With MotorCortex.js, external *.mss files determine animation parameters. These are based on the CSS parameters that are supported by Velocity.js:

.section:myEvent{
  duration: 400;
  top: 300px;
}

For more examples with the associated CSS and JavaScript, see http://motorcortexjs.com/#examples.

Testing AngularJS with Jasmine

David Posin sent in Angular and Jasmine: Injecting into the test environment. He’s been using Jasmine for tests in both Node and client-side JavaScript, so he wanted to use it with Angular as well:

Angular requires a very specific environment in which to function. The result of that can be a significant amount of boilerplate when creating tests for Angular applications in Jasmine. The good news is that the amount of redundancy can be minimized with careful test organization.

The way he does this is by creating embedded suites:

The spec file will have one describe that contains that spec’s entire content. Inner describe clauses will be used to manage and break up the tests. Inside of the main over-arching describe we will add variables to contain the services that all the clauses will need.

I too find it frustrating to have to switch my preferred test library because of a framework’s design, so it’s interesting that he managed to get Jasmine working in the end. It can be quite hard to think the Angular way for relative newcomers.

Receiving Emails with Node

05 Jun 2014 | By Alex Young | Comments | Tags node modules npm email servers

One of the things I like to evangelise about Node is the fact it’s good for creating any network servers, not just web stuff. Florent Galland sent in Mailin (GitHub: Flolagale / mailin, License: MIT, npm: mailin), which allows your web apps to receive inbound emails. What’s cool about Mailin is it runs as an SMTP server, so rather than having to configure a mail server you can just use Mailin by itself.

Mailin’s homepage has a cool demo that allows you to send it an email and see it appear on the page. This works using Mailin’s webhook.

Mailin

You can configure the webhook when the server is started:

mailin --webhook http://example.com/incoming_emails

The documentation explains how to install it with authbind for safe binding to port 25, otherwise sudo or a root user would be required.

The documentation also mentions optional spam detection support.

Mailin is built with the simplesmtp module. This provides a Node API for building SMTP servers. It has an API that should be familiar to anyone who has written HTTP code with Node:

simplesmtp.createSimpleServer({ SMTPBanner: 'My Server' }, function(req) {
  req.pipe(process.stdout);
  req.accept();
}).listen(port);

simplesmtp even supports connection pools, and TLS. I love the idea of using Node for servers that I can customise, but I’m not a security expert so I don’t know what the implications of using these modules in production might be. Maybe it’s time I read Node Security!

Node Roundup: browser-perf, node-modules, module.exports vs. exports

04 Jun 2014 | By Alex Young | Comments | Tags node modules npm

browser-perf

browser-perf (GitHub: axemclion / browser-perf, License: BSD-2 Clause, npm: browser-perf) by Parashuram Narasimhan is a Node-based browser performance testing tool. It collects various metrics from browsers and then displays graphs using the results.

It runs as a command-line script which allows you to specify which browsers you’d like to use:

browser-perf http://example.com --browsers=chrome,firefox --selenium=ondemand.saucelabs.com --username=username --accesskey=accesskey

There’s also a Node API:

var browserPerf = require('browser-perf');
browserPerf('http://example.com/test', function(err, res) {
  // res - array of objects. Metrics for this URL
  if (err) {
    console.log('ERROR: ' + err);
  } else {
    console.log(res);
  }
}, {
  selenium: 'http://localhost:4444/wd/hub',
  browsers: ['chrome', 'firefox']
  username: SAUCE_USERNAME
});

There’s a wiki page with more details.

The author has also written a blog post about browser-perf with a screenshot.

node-modules.com

Gregor Elke sent in node-modules.com, an alternative search engine for npm. It was created by Mathias Buus Madsen and Tobias Baunbæk, and supports GitHub sign in for customisation. It only requires access to your public details, and seems to sort results fairly well.

module.exports vs. exports

Cho S. Kim sent in a post about understanding module.exports and exports:

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file. The keyword require returns an object, which references the value of module.exports for a given file. If a developer unintentionally or intentionally re-assigns module.exports to a different object or different data structure, then any properties added to the original module.exports object will be unaccessible.

Mock APIs with APItizer

03 Jun 2014 | By Alex Young | Comments | Tags testing jquery

When I’m developing APIs for desktop and mobile projects, I’ve found some people like to mock up APIs in tools like Apiary first. This allows non-web developers to create API specifications that can generate sample data for actual HTTP requests.

Sometimes when you’re doing client-side development you want something similar. APItizer, by Mihael Konjević lets you mock APIs with a JSON schema, so you can try out requests from libraries like jQuery without having to hassle a server-side developer.

When developing single page apps, it is beneficial to develop frontend and backend in parallel. To achieve that, you need to mock the API. CanJS implements this elegantly with the can.fixture plugin (used by APItizer). can.fixture intercepts Ajax calls and returns response defined by the fixtures.

To mock an API you need three things:

  1. A JSON schema
  2. To register it with APItizer: apitizer.addSchema('user', schema)
  3. Some sample data: apitizer.fixture.resource('/users', apitizer.schemaStore('user', 10))

Schemas just need to define the properties used by your resources:

var schema = {
    type: 'object',
    properties: {
        id: {
            type: 'integer'
        },
        username: {
            type: 'string'
        },
        password: {
            type: 'string'
        }
    }
};

This will give you some sample users that you can interact with using the standard RESTful CRUD routes.

APItizer also allows you to add custom endpoints and response delays, so you can simulate network latency. Full examples can be found in the project’s readme file.

If you’re working on a UI-heavy Knockout or Angular project, then this might help avoid worrying too much about the server as you try out UI ideas.

Searching npm

02 Jun 2014 | By Alex Young | Comments | Tags npm node

My book is currently going through technical proof reading, so I’ve been getting lots of interesting feedback. One small thing the reviewer noted was that npm search express generates thousands of results, so he asked how to filter the results.

The documentation for npm search shows that queries can use regular expressions. In my shell I have to escape regular expressions with single quotes. That means I can search for packages that start with “express” like this:

npm search '/^express/'

That reduces the output to 623 results. Perhaps, however, the issue was really relevance. Lots of results aren’t so bad if they’re sorted in a reasonable way. I tried npmsearch which you can install with npm install npmsearch, and the results seemed very friendly. You can even control the output with options like --freshness and --aging.

There’s also nipster, which combines npm’s results with GitHub. It feels fast, but it’s actually a pretty simple client-side project.

Another thing to note is npm’s standard search combines various fields (description, keywords, url) to create keywords, so you can’t easily search on a specific field (unless I’m mistaken). I’d like to search for something like name:express, but I can’t do that yet.

If you have any cool npm search-related tricks, please let me know!

Crunch, NodeRT

30 May 2014 | By Alex Young | Comments | Tags node mathematics

Crunch

Crunch (GitHub: vukicevic / crunch, License: MIT) by Nenad Vukicevic is an arbitrary-precision integer arithmetic library, with a focus on speed. It has no dependencies, and the project includes examples for finding prime-numbers, generating keys for RSA, encryption, and decryption.

The examples also demonstrate using WebWorkers with the library, so you could farm out mathematical operations to multiple workers. Crunch includes unit tests and documentation in the readme file.

NodeRT

NodeRT is a WinRT module generator for Node:

NodeRT automatically exposes Microsoft’s WinRT APIs to Node.js by generating Node modules. This enables Node developers to write code that consumes native Windows capabilities. The generated APIs are (almost) the same as the WinRT APIs listed in MSDN.

This is an example of windows.devices.geolocation:

var geolocation = require('windows.devices.geolocation');
var locator = new geolocation.Geolocator();

locator.getGeopositionAsync(function(err, res) {
  if (err) {
    console.error(err);
    return;
  }

  console.info('(', res.coordinate.longitude, ',',  res.coordinate.latitude, ')');
});

The project has fairly detailed documentation in the readme, including the requirements which includes VisualStudio 2013.

Velocity UI Pack

29 May 2014 | By Alex Young | Comments | Tags animations ui jquery

Julian Shapiro has announced the Velocity UI Pack. There’s a screencast that introduces the effects and how to use them.

This is an additional dependency for the Velocity.js library, which is a performance-focused jQuery plugin that improves on $.animate(). With the Velocity UI Pack you can perform animations on sets of elements, which is ideal for drawing attention to content as it’s loaded using Ajax.

It supports a stagger option which adds a delay after each animation. Given a set of elements, you can apply an animation in sequence simply by using $divs.velocity('callout.shake', { stagger: 75 }). If you’re loading an array of records using Ajax, then you can render the resulting elements and display them with .velocity('anim', { stagger: time }).

One thing that I like about this library is the animations don’t result in blurry text. Julian has gone to a lot of trouble to make it easy to use and fast, so it’s worth checking out the demo and the screencast.

Node Roundup: mongo-select, asynctrace

28 May 2014 | By Alex Young | Comments | Tags node modules npm testing mongodb

mongo-select

mongo-select (GitHub: dschenkelman / mongo-select, License: MIT, npm: mongo-select) is a module for creating projections on results from mongodb.

You can specify the fields to include using select.include:

var select = require('mongo-select').select();
var projection = select.include(['name', 'email', 'children.name']).make();

console.log(projection); // { 'name': false, 'email': false, 'children.name': false };

There are also methods for excluding fields (exclude) and ignoring the _id field (noId). These methods can be chained:

select.noId()._exclude(['name', 'email', 'children.name']);

Using it with MongoDB queries looks like this:

var select = require('mongo-select').select();
var mongodb = require('mongodb');

var MongoClient = mongodb.MongoClient;

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
  if (err) throw err;

  var users = db.collection('users');

  users.find(
    {},
    select.include(['name', 'email']),
    function(err, result) {
      // code here, access to only result[i]._id, result[i].name and result[i].email
    }
  );
});

asynctrace

asynctrace (GitHub: Empeeric / asynctrace, License: MIT, npm: asynctrace) from Empeeric is a stack trace API based on AsyncListener. By requiring asynctrace, you’ll get stack traces that include details on asynchronous boundaries.

It’s built using the shimmer module, which is meant to help safely replace functions by wrapping them.

If you use Mocha then you can optionally use it by specifying it on the command line: mocha --require asynctrace. That means you don’t need to modify your code to use the module during testing.

Fluxxor for React

27 May 2014 | By Alex Young | Comments | Tags reactive facebook
Flux

Fluxxor (GitHub: BinaryMuse / fluxxor, License: MIT, Bower: fluxxor) by Brandon Tilley is a library designed to work with Facebook’s React. It provides an application architecture that’s based around a dispatcher, stores, and views.

Instantiating a Flux application looks like this:

var flux = new Fluxxor.Flux(stores, actions);

The stores object contains classes that are created with Fluxxor.createStore, and the actions object is a set of methods that invoke that dispatcher:

var actions = {
  addTodo: function(text) {
    this.dispatch("ADD_TODO", {text: text});
  },

  toggleTodo: function(todo) {
    this.dispatch("TOGGLE_TODO", {todo: todo});
  },

  clearTodos: function() {
    this.dispatch("CLEAR_TODOS");
  }
};

These examples were taken from the Fluxxor quick start guide, which explains how to write a to-do list with Flux.

Fluxxor provides more tools as well. Fluxxor.FluxMixin can be used to make Flux instances available to React components, and Fluxxor.StoreWatchMixin allows you to watch for change events on Flux stores.

You can use Fluxxor outside of React, and it’s installable with Bower as fluxxor. Brandon, the author of the library, pointed out that Fluxxor is his personal implementation of the Flux pattern which was created by Jing Chen at Facebook.

ngActivityIndicator, angular-cog, dijs

26 May 2014 | By Alex Young | Comments | Tags angularjs di ajax

ngActivityIndicator

ngActivityIndicator

ngActivityIndicator (GitHub: voronianski / ngActivityIndicator, License: MIT) by Dmitri Voronianski is an Angular provider for loading indicators, which you can use on directives, controllers or services.

Adding an indicator to a controller looks like this:

var app = angular.module('exampleApp', ['ngActivityIndicator']);

app.controller('MainCtrl', ['$activityIndicator', '$timeout',
  function ($actvityIndicator, $timeout) {
    $actvityIndicator.startAnimating();
    $timeout(function () {
      $actvityIndicator.stopAnimating();
    }, 3000);
  }
]);

There’s a directive called ng-activity-indicator which can be used to inject the indicator into the DOM automatically.

angular-cog

angular-cog (GitHub: chinmaymk / angular-cog, License: MIT) by Chinmay Kulkarni is a library for writing declarative Ajax requests with Angular.

The full set of directives are as follows:

<div cog-verb="{url}" 
        cog-model="{ng-model}" 
        cog-success="{angular.expression}" 
        cog-error="{angular.expression}"
        cog-trigger="{angular.expression}"
        cog-no-spinner="{true|false}" 
        cog-absolute-url="{true|false}" 
        cog-config="{object}">
</div>

Requesting JSON content should place it in the $data variable, so you can access it in cog-success and then pass it to something bound in $scope.

The documentation includes notes on how to set up a loading indicator – maybe you could try ngActivityIndicator?

dijs

dijs (GitHub: cmtt / dijs, License: WTFPL) by Matthias Thoemmes is a dependency injection module for Node and browsers that’s inspired by Angular. There are methods for defining a namespace, describing the modules, and resolving dependencies.

For describing dependencies, it supports function notation and array notation:

// Function notation
var mod = Di();
mod.provide('Pi', Math.PI, true);
mod.provide('2Pi', function(Pi) { return 2*Pi; });

// Array notation
var mod = Di();
mod.provide('Math.Pi', Math.PI, true);
mod.provide('2Pi', ['Math.Pi', function (Pi) {
  return function () {
    return 2*Pi;
  };
}]);

There’s a lot more to it than this, and you might find it useful if you’ve got used to DI through Angular but want to use it elsewhere.

Ramda, AniJS ScrollReveal

23 May 2014 | By Alex Young | Comments | Tags functional libraries animation

Ramda

Ramda

Ramda (GitHub: CrossEye / ramda, License: MIT, npm: ramda) by Scott Sauyet and Buzz de Cafe is a functional library that is similar to Underscore, but has a very different API style.

In Underscore you might filter arrays like this:

var validUsersNamedBuzz = function(users) {
  return _.filter(users, function(user) { 
    return user.name === 'Buzz' && _.isEmpty(user.errors); 
  });
};

But in Ramda you can pass the function first and the array last:

var validUsersNamedBuzz = R.filter(R.where({ name: 'Buzz', errors: R.isEmpty }));

All of Ramda’s functions curry automatically, which makes composition easier:

Because the API is function-first, data-last, you can continue composing and composing until you build up the function you need before dropping in the data. (Hugh Jackson published an excellent article describing the advantages of this style.)

These API decisions mean Ramda feels like native JavaScript with less syntax than you might expect.

ScrollReveal Using AniJS

ScrollReveal (GitHub: anijs / examples / scrollreveal) by Dariel Noel Vila Plagado is an AniJS helper function that animates components as they enter the viewport.

The syntax for animating items looks like this:

<div id="item" data-anijs="if: scroll, on: window, do: swing animated, before: scrollReveal">
  Cuba 2022
</div>

Node Roundup: webpack, Mitm.js, musicmetadata

22 May 2014 | By Alex Young | Comments | Tags node modules npm build-systems network

webpack

webpack

Vignesh Anand sent in webpack (GitHub: webpack, License: MIT, npm: webpack) by Tobias Koppers. It’s a bundler for CommonJS and AMD packages, based around asynchronous I/O, and supports preprocessors like CoffeeScript.

With webpack you can load chunks of dependencies on demand, so you can reduce the initial payload. It only supports JavaScript by default, but there are modules for loading resources like CSS (css-loader). To understand how it works, the getting started tutorial provides a high-level overview.

Vignesh pointed out that Instagram uses webpack, and it already has a lot of support on GitHub.

Just wanted to leave a little thank you and share the exciting news that instagram.com is now building and serving all of its js and css assets with webpack :). @sokra you’ve been an awesome help in getting this all working, and our build step is so much cleaner and quicker because of it.

Mitm.js

Mitm (GitHub: moll / node-mitm, License: LAGPL, npm: mitm) by Andri Möll is a module for intercepting and mocking outgoing TCP and HTTP connections. Running Mitm() will enable mocking for sockets, and it returns an object that allows mocking to be disabled:

var Mitm = require('mitm');
var mitm = Mitm();

// Later:
mitm.disable()

The documentation has more examples, including how to handle HTTP requests during testing.

musicmetadata

musicmetadata (GitHub: leetreveil / musicmetadata, npm: musicmetadata) by Lee Treveil is a streaming metadata parser for music files:

var fs = require('fs');
var mm = require('musicmetadata');

// create a new parser from a node ReadStream
var parser = mm(fs.createReadStream('sample.mp3'));

// listen for the metadata event
parser.on('metadata', function(result) {
  console.log(result);
});

The project is a fork of node-id3 by António Afonso.

Script-injected Async Scripts Considered Harmful

21 May 2014 | By Alex Young | Comments | Tags async performance

Ilya Grigorik has published a post about how script-injected resource loading could negatively impact performance, in Script-injected “async scripts” considered harmful.

The inline JavaScript solution has a subtle, but very important (and an often overlooked) performance gotcha: inline scripts block on CSSOM before they are executed. Why? The browser does not know what the inline block is planning to do in the script it is about to execute, and because JavaScript can access and manipulate the CSSOM, it blocks and waits until the CSS is downloaded, parsed, and the CSSOM is constructed and available.

The example in the article shows a CSS download blocking script execution, where the scripts are short snippets that inject additional script elements to load real JavaScript files. The delay of execution causes the files to be downloaded later than desired.

If you look at the source to DailyJS you can see Disqus injecting a script that way, and when I look at the network tab in Chrome Developer Tools it seems like count.js executes after the CSS files have downloaded.

The obvious fix is to use async attributes on script tags, as long as you can live with the additional effort to support IE8 and 9. But before you rush off to reformat your sites, the last point by Ilya is interesting:

Wait, should I just move all of my JavaScript above the CSS then? No. You want to keep your <head> lean to allow the browser to discover your CSS and begin parsing the actual page content as soon as possible - i.e. optimize the content you deliver in your first round trip to enable the fastest possible page render.

Optimising for all possible browser behaviours is difficult!

Hammer.js: touch-action fix

20 May 2014 | By Alex Young | Comments | Tags mobile touch

Hammer.js has been updated, and the authors have written a notice about the scrolling behaviour in Chrome 35 and IE10. The touch-action CSS property controls how regions are scrolled with touch events – think panning and zooming.

In older versions of Hammer, this property was set to none, so it blocked scrolling. You can change the default behaviour using the behavior.touchAction property:

<script src="hammer.js"></script>
<script>
// enable only vertical scrolling on browsers that support touch-action
// for 1.0.x this is at the stop_default_behavior object
Hammer.defaults.behavior.touchAction = 'pan-y';

// ...your hammer code...etc...
var mc = new Hammer(document.body);
</script>

Realising that this would confuse people, the Hammer authors have written How to fix Chrome 35 and IE10 scrolling, so you can update your Hammer-based sites to work correctly in newer browsers.

Async Harmony Tests

19 May 2014 | By Alex Young | Comments | Tags es6 async firefox

Simeon Velichkov sent in async-harmony tests (GitHub: simov / async-harmony, License: MIT), which contains examples of new ES6 features. Each example is based on methods from async, but written using new features like generators, including arrow functions.

It only currently works in Firefox 29, but I thought the examples were quite interesting:

function eachSeries (items, job, done, kill=true) {
  var results = [], errors = [];

  var it = iterator();
  it.next();

  function* iterator () {
    for (let item of items) {
      yield job(item, (err, result) => {
        if (kill && err) return done(err);
        if (err) errors.push(err);
        results.push(result||null);
        setTimeout(() => it.next(), 0);
      });
    }
    done((errors.length ? errors : null), results);
  }
}

The corresponding usage looks like this:

async.eachSeries([0,1], (item, done) => {
  done(new Error('error'+item));
}, (err, result) => {
  err.message.should.equal('error0');
  done();
});

Give them a read if you’re interesting in seeing ES6 in action.