03. November 2015

Keo

Keo (GitHub: Wildhoney/Keo, License: MIT, npm: keo)

https://github.com/Wildhoney/Keo/raw/master/media/screenshot.png

If you are like me and don’t like the ESnext syntactic sugar which gets used in most React examples nowadays, then you will like Keo. Keo gives you a more functional approach to creating React components.

The advantages gained by using Keo are:

  • Steer away from class
  • Create referentially transparent, pure functions without this
  • Use export to export plain functions for simpler unit-testing
  • Simple composing of functions for mixin support
  • Avoid functions being littered with React specific method calls

Keo’s philosophy is that you should not have to worry about the this keyword (even though scoping has became a lot better since ES2015). As such, Keo takes a more Deku approach in that items such as props, state, setState, et cetera are passed in to some React lifecycle functions.

The React lifecycle functions such as: componentWillMount, componentDidMount, componentWillUnmount, render will receive props, state, setState and dispatch as an object which can be destructured.

When you have created your component, Keo encourages you to export all functions so that you can test each one individually, but demands that you export the lifecycle functions by invoking keo.stitch like this:

import {stitch} from 'keo';
// ...
export default stitch({ componentDidMount, render });

You could still use Redux with Keo. Keo provides a keo/redux adapter for handling Redux in a more succinct fashion. Instead of importing keo you can import the keo/redux adapter and use the stitch function from there instead like this:

import {stitch} from 'keo/redux';
// ...
export default stitch({ componentWillMount, render }, state => state.zombies);

02. November 2015

Stream.js

Stream.js (GitHub: winterbe/streamjs, License: MIT, npm: streamjs, bower: streamjs)

Stream.js is a lightweight functional library for operating on in memory collections. It requires ES 5+, but has built-in support for ES6 features it works in all current browsers, Node.js and Java 8 Nashorn.

This library is built around a lazily evaluated operation pipeline. Which means that instead of consecutively performing each operation on the input collection, objects are passed vertically and one by one into the chain. Interim results will not be stored in internal collections. Instead objects are piped into the result object.

Stream’s operations are lazily evaluated to avoid examining all of the input data when it’s not necessary. For instance with a filter - map - findFirst stream you don’t have to filter and map the whole data. Instead map and findFirst are executed just one time before returning the single result. This results in way better performance when operation upon large amount of input.

Like this:

Stream([1, 2, 3, 4])
   .filter((num) => {   // called twice
      return num % 2 === 0;
   })
   .map((even) => {     // called once
      return "even" + even;
   })
   .findFirst();        // called once

Because this library has a very extensive API, I will not be discussing that today and I will just refer you to the API Docs provided by the developer

29. October 2015

generator-redux

generator-redux (GitHub: banderson/generator-redux, License: MIT, npm: generator-redux)

Today I like to mention a Yeoman generator which I’ve being using a lot lately: generator-redux. When you are not familiar with Yeoman please check it out, it will save you a lot of time.

You have probably heard about Facebook’s Flux architecture. Since a few months there is a new kid in town called Redux. Redux is “Atomic Flux with hot reloading”. A next-generation take on the Flux pattern with some core design differences such as:

  • Preserves the benefits of Flux, but adds other nice properties thanks to its functional nature.
  • Prevents some of the anti-patterns common in Flux code.
  • Works great in universal (aka “isomorphic”) apps because it doesn’t use singletons and the data can be rehydrated. …

The features included in this generator are:

  • Redux functional application architecture
  • Redux-DevTools configured and enabled when in dev mode
  • WebPack for build pipeline and dev server awesomeness
  • Babel transpiler so you can use bleeding edge language features
  • PostCSS preprocessor with autoprefixer support

Offcourse this generator depends on yo being installed globally. Once you have that you can acquire it via:

npm install -g generator-redux

Now that the generator is installed you can access it via:

yo redux

This will give you a prompt asking you for an application name, description and a port. Description is used in package.json and the generated README.md. Port is to run your development server on (defaults to 3000).

To start the scaffold app use:

npm run

When you wanna run it with the Redux-DevTools enabled use:

DEBUG=true npm start

28. October 2015

vstack-validator

Vstack-validator (GitHub: vslinko/vstack-validator, License: MIT, npm: vstack-validator)

When you are working with very complex and deeply nested data structures, validation can become a real pain. Vstack-validator tries to solve this problem by providing you with a declarative API which consists of 3 methods: a validator, a constraint and a schema. The Validator is a function that receives a value and returns boolean result of validation. Constraint is a function that receives a value and returns validation metadata. With a Schema we create declarations of the constraints in a tree, which in turn can be used to validate an object, which would look like this:

import {schema} from 'vstack-validator';

const userSchema = schema.type('user', {
    email: {
        notEmpty: schema.constraint(schema.validators.isNotEmpty, 'Email is empty'),
        email: schema.constraint(schema.validators.isEmail, 'Email is not valid'),
    },
    password: schema.optional({
        notEmpty: schema.constraint(schema.validators.isNotEmpty, 'Password is empty'),
        minLength: schema.minLength(3, 'Password is less than 3'),
    }),
});

const itemSchema = schema.type('item', {
    name: {
        notEmpty: schema.constraint(schema.validators.isNotEmpty, 'Name is empty'),
    },
});

const cartSchema = schema.type('cart', {
    user: userSchema,
    items: schema.list(itemSchema),
});

let validationData = {
    user: {
        email: '',
        password: '',
    },
    items: [
        { name: '' },
    ],
};

cartSchema.check(validationData)
          .then((constraintResult) => console.log(constraintResult));

When the check is executed constraintResult it would look something like this:

{
    valid: false,
    message: 'Objectisnotvalid',
    children: {
        user: {
            valid: false,
            message: 'Objectisnotvalid',
            children: {
                email: {
                    valid: false,
                    message: 'Valueisnotvalid',
                    children: {
                        notEmpty: {
                            valid: false,
                            message: 'Emailisempty',
                            children: null
                        },
                        email: {
                            valid: false,
                            message: 'Emailisnotvalid',
                            children: null
                        }
                    }
                },
                password: {
                    valid: false,
                    message: 'Valueisnotvalid',
                    children: {
                        notEmpty: {
                            valid: false,
                            message: 'Passwordisempty',
                            children: null
                        },
                        minLength: {
                            valid: false,
                            message: 'Passwordislessthan3',
                            children: null
                        }
                    }
                }
            }
        },
        items: {
            valid: false,
            message: 'Arrayisnotvalid',
            children: [
                {
                    valid: false,
                    message: 'Objectisnotvalid',
                    children: {
                        name: {
                            valid: false,
                            message: 'Valueisnotvalid',
                            children: {
                                notEmpty: {
                                    valid: false,
                                    message: 'Nameisempty',
                                    children: null
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
}

27. October 2015

jsdoc2diagram

jsdoc2diagram (GitHub: amcmillan01/jsdoc2diagram, License: MIT, npm: jsdoc2diagram)

If your day job looks anything like mine, the problem of sharing knowledge will be a well known issue for you. We try our best to keep the docs up to date and inform our co-workers of any changes that would be crucial. But what if a new developer joins the team? He will be spending the next week or 2 getting the know the entire app but mostly how everything hangs together.

Since we are probably already using JSDoc there is a great addition available for giving insight on how the application is put together called jsdoc2diagram.

What jsdoc2diagram does is literally what the name implies it does. It turns JSDocs documentation into graphs using d3.js.

This is an example of the kind of graph it would present you with:

The for for this diagram looks like this:

/**
 * @constructor
 */
var Garage = function(){

};

/**
 * @return {number}
 */
Garage.prototype.getVehicleCount = function(){

};


/**
 *
 * @constructor
 * @memberof Garage
 */
var Car = function(){
  /**
   *
   * @type {string}
   */
  this.name = '';
  /**
   *
   * @type {string}
   */
  this.color = '';
};

/**
 * @return {boolean}
 */
Car.prototype.isOn = function(){

};

/**
 * @return {boolean}
 */
Car.prototype.hasNavigation = function(){

};

I think this is a great addition to every bit of documentation. It gives a clear overview of how objects and methods are in relation to each other, which is something I was really missing.

To get started using this you will need to have jsdoc installed once you have that you only need to install jsdoc2diagram via npm and then you could use it like this:

jsdoc -t PATH/TO/jsdoc2diagram -r JS_SOURCE_DIR/FILE -d OUTPUT_DIR

I could imagine that you would call this from an npm run script after your JSDocs are generated.