Fork me on GitHub

A Guide to Getting Started

nanoscope is a javascript library designed to make complex transformations of data much easier. It is a built on the idea of a functional Lens -- a construct that enables focusing on sub-parts of data structures to get and modify. nanoscope is a collection of these so-called Lenses boxed up into a convenient package with a simple, intuitive interface.

var nanoscope = require('nanoscope');


game = {
    player: {
        location: { x: 6, y: 10},
        color: 'Yellow',
        unnecessaryInformation: 'nobody-cares'
    },
    enemies: [
        {
            location: { x: 10, y: 20 },
            name: 'Pinky',
            traits: ['Mischievous','Persistent', 'Tricky']
        },
        {
            location: { x: 2, y: 22 },
            name: 'Clyde',
            traits: ['Ignorant', 'Goofy', '##$@??']
        }
    ],
    pelletLocations: [{ x: 10, y: 12 }, {x: 11, y: 15 }]
};

var lens = nanoscope(game);




game = lens.path('player.name.first').set('Pac-Man');










var firstGhostX = lens.following('enemies')
    .indexing(0)
    .following('location.x')
    .get();





game = lens.following('player.location')
    .plucking(['x', 'y'])
    .map(function (coordinate) {
        return coordinate + 1;
    });



var clydesTraits = lens.path('enemies')
    .filter(function (enemy) {
        return enemy.name === 'Clyde';
    })
    .index(0)
    .path('traits')
    .filter(/[a-zA-Z]/)
    .get();

First, require nanoscope.

Suppose we have a simple representation of a game of Pac-Man in front of us that someone built using raw dynamic objects. We have some garbage to locate and get rid of, and perhaps we want to modify the game in some way.

First, we construct a lens that looks into our game object.

We can use path to look into a nested object, and set to modify it. set returns a modified game, so we set it here. Notice that we're setting a property that you might expect to throw an error -- with nanoscope, modification proceeds safely, and our player's first name is set to 'Pac-Man'

Here, we focus on the location of the first enemy in the enemies table, and pull out its x coordinate. following is an alias for path; nanoscope has many aliases like these so you can use it in whatever way is most comfortable.

We can use plucking to focus on on specific properties of an object and transform them. This increments the player's x and y coordinates and returns a new game object.

There are many more functions we can use to further prune data. Here, we find Clyde and extract his traits -- well, all of the traits that consist only of letters -- using filter. If Clyde didn't exist in the enemies list, nanoscope wouldn't care; this would just return [] instead of failing catastrophically.

This is just the tip of the iceberg when it comes to nanoscope. Refer to the API Documentation for more cool stuff that you can do with the library. Have fun!