Gitbook.io

GitBook.io is a web-based service designed to revolutionize the writing / authoring process. It is a tool for using Markdown to write books, which are converted to dynamic websites or exported to static formats like PDF. If also introduces a social dimension to the book creation process by providing integration with Git and GitHub.

To simplify its workflow, Gitbook.io provides the Gitbook Editor, a cross-platform tool for creating and formating your ebook using Markdown. Ebooks are stored as plain-text, markdown-formatted files in your book folder; and can thus be converted into a Git repository and use Git functionality for versioning, synchronization, and collaboration with other contributors.

Using the editor, you can iteratively push your book up to the Gitbook.io service, which then builds the ebook and generates formats compatible with Amazon Kindle, Nook and readers supporting PDF, ePub and Mobi formats. Books can be offered free or sold, with the service also bearing the burden of processing the payments and charging a percentage of sales per transaction.

It may seem like a put-off to non-developers to use Markdown and Git but the ease of writing and publishing it offers are too much of a benefit to forego.

Emmet

Emmet, previously known as Zen Coding, is “a set of plug-ins for text editors that allow for high-speed coding and editing in HTML, XML, XSL, and other structured code formats via content assist“.

It’s ability to instantly expand simple abbreviations into complex code snippets is what enables Emmet to make you a more productive developer and has gained it a cult-like following amongst developers.

Started by Vadim Makeev in 2008, it has been incorporated into most high-profile text editors.

Some of the functionality Emmet provides include:

  • Expand abbreviations
    Emmet uses a specific syntax in order to expand small snippets of code, similar to CSS selectors, into full-fledged HTML code. The expand abbreviations function includes several other complex functions, such as wrapping a section of code with expanded code.
  • Tag balancing
    The HTML Pair Matcher allows users to locate the matching open/close tag for the tag at the current cursor position. Unlike other HTML pair matchers, Emmet searches from the cursor’s current position rather than scanning the document from the beginning.

To advance your Emmet knowledge, consider to the following resources:

To Grunt or to Gulp: the JavaScript Taskrunner Wars

Quoting Travis Maynard, “Task runners are small applications that are used to automate many of the time consuming, boring (but very important) tasks that you have to do while developing a project. These include tasks such as running tests, concatenating files, minification, and CSS preprocessing. By simply creating a task file, you can instruct the task runner to automatically take care of just about any development task you can think of as you make changes to your files. It’s a very simple idea that will save you a lot of time and allow you to stay focused on development.

The rapid pace of tools development to simplify programming recently shifted to the build systems. Grunt, the trustworthy taskrunner, now has a challenger for the heart of web developers in the person of Gulp, the newest bride on the block.

Grunt is a configuration-based system which uses a Gruntfile in your document root to manage its configuration options. Most features are provided as addons using plugins. One of the major complaints about Grunt is the abundance of configuration required to achieve simple tasks.

Gulp on the other hand adopted the programmatic approach. It utilises a similar layout structure as Grunt (one Gulpfile and features added through plugins), but works based on the concept of Streams. In Gulp, your code as a set of files that require a series of operations performed on them. Once an operation is finished, a stream is used to pipe its result to the next operation to be executed.

Two main points favoring Gulp adoption today are Speed of Execution and Code over Configuration. Gulp has a noticeable execution speed over Grunt; it is expected that newer releases will narrow the gap. And for those who would rather write code than maintain configuration files, Gulp is also the way to go.

One advantage that Grunt currently has over Gulp is a much wider community support, with a lot more plugins available for it. This though is fickle, and can change as Gulp sees more adoption by developers.

“The most important question to ask yourself is which philosophy do you subscribe to more? Do you like a build system that prefers code over configuration? If so, then you may feel right at home with Gulp. Otherwise, stick with Grunt”.

Editor Smackdown: Sublime Vs Atom

Sublime_Text_Logo              vs              atom-logo

SublimeText has had a great reign; it is indeed a marvelous piece of software, hands-down one of the best cross-platform editors. But, like every good product is bound to have, there is a new contender making waves at the moment: GitHub’s Atom. The question then is: will Sublime continue to reign as the undisputed king of the editors?

Atom, promoted as “A hackable text editor for the 21st century”, is an all web based desktop app built on top of Chromium, Google’s open-source web browser. Written using Node.js, CoffeeScript, LESS and then wrapped in a WebKit wrapper, it currently runs on OS X, Windows and Linux.

Atom is an attempt to marry the beauty of Sublime with the ubiquity of JavaScript. The UI and functionality is basically a mirror of Sublime, the plugin system is cool, and a great community has already built up around it.

Sublime on the other hand went the native route as it’s core is written in C/C++ using a Python API for plug-ins. Though similar in UI and UX, its native nature accounts for why Sublime performs significantly better than Atom especially in “heavy lifting” like working with large files, as Atom still has a max of 2MB file load.

Sublime also outperforms Atom in terms of responsiveness. Be it typing within the document, switching tabs, or opening files, you will definitely notice the slight delays Atom’s web based foundation exhibits.

In this area of speed, the technology stack underlying Atom may yet be its greatest enemy. But with it’s open-source nature and the backing of Github, I believe there will be improvements as Atom matures.

Atom is beautiful, but it’s performance is being hobbled by platform choice. Sublime has raised the bar very high and I’m pretty sure for the time being, a non-native app will not be able to compete.

So till these issues are resolved, Sublime IMO ever so gingerly retains his crown as the King of the Editors.

Introducing Sails: the Realtime Node Framework

Sails3

Sails is an MVC framework built on the simplicity of Node, the beauty of Express and the chattiness of Socket.IO. It’s like a Ruby on Rails for JavaScript and even comes with a pretty powerful commandline interface for issuing such commands as sails new myApp to create a new application.

Built on top of Express, Sails inherits its incredible performance and consistency and numerous modules, like the Express router, cookie parser, body parser. Thus developing routes / REST APIs is insanly quick.

Sails also provides realtime features with the integration of WebSockets and Socket.IO out of the box.

To ease development, Sails uses the Waterline ORM to abstract data access to SQL and NoSQL databases. The data-agnostic nature of the ORM makes it easy to mix and match datastores, so you can have some models stored in MySQL and others in Redis. It provides validation and some level of association between joins. It is easy to write custom methods on your models to extract “higher-order” data from them. But most importantly, creating a model gives you a ton of routes (CRUD blueprints and REST endpionts) out of the box (and they all work with Websockets!).

Sails also encourages using consistent conventions for structuring files across applications. This ideally enhances productivity, especially when working in a team. It’s better for stakeholders because it means you do less inventing and more practical work, it’s easier to get new programmers up to speed on how existing codebases work, and it allows a team to encourage/enforce coding best-practices.

In all, with its beautiful mix of technologies and some stronger conventions for app development, Sails is indeed a Node framework to look into.

Why MEAN: the rise of JavaScript

The era of Web 2.0 is gradually drawing to a close. Pockmarked by the reign of Ruby on Rails, PHP (and its many frameworks), Web 2.0 apps had a clear delineation in roles between the server and client portions.

Today, we are seeing a rise in the demand for apps that provide instant, real-time features previously found only in desktop applications. Most interactivity on the web were restricted to Java applets, Flash and the bad-child of the web, JavaScript.

In it’s early days, JavaScript took a lot of bashing, and was relegated to the “me-too” status by a lot of developers, the writer included. It was looked down on, but as is oft the case, today it has the last laugh.

The creation of the the V8 JavaScript engine by Google sparked a maddening surge in the current renaissance of JavaScript. With the invention of Node.js by Ryan Dahl based on the V8 engine, all hell was literally let loose. Suddenly, the rejected stone became the chief cornerstone.

Since server-side programming was possible in JavaScript, what about the data-layer? The march of NoSQL began, with heavyweights like MongoDB, Couch etc spawned and created to ride the wave.

On the client-side, an avalanche of frameworks were born. From the grand-old king (jQuery), newer contenders came forth – Backbone, Ember, Angular, Knockout etc

Ubiquity was within reach, as a developer just needed to learn 1 language: JavaScript.

Not done with his victory, JavaScript turned his eye to one of the companies who started it all: Microsoft. Windows 8 soon came, and with it, a native API for developing in JavaScript. Oh, the sweet smell of victory.

One final frontier: the mobile. Predictions placed mobile as the next big thing, and JavaScript loved the sound of it. He tuned in to the challenge and viola we had a slew of technologies enabling mobile development in JavaScript. PhoneGap/Cordova, Ratchet, Crosswalk et al are all off-springs of the JS/Mobile union.

Then GIS and mapping, game engines, visualization libraries, telephony API’s, the list becomes endless.

A web developer going into the 21st century then has a dilemma: what do I learn? Short answer, Go MEAN. Mongo for your database, Express and Node for server-side and Angular for the client-side. It is amazing the productivity gains you get from focusing on one language and not having to switch context regularly.

Like Julius Caesar, JavaScript can finally boast “I came, I saw, I conquered”. We are all at his mercy.

Applicative  Programming in JavaScript with Underscore.js

Introduction to Applicative Programming

Applicative programming is a technique that allows a function to be applied to each element of a list. It is a pattern of defining a function that takes a function and then invokes that function for each element in a collection/list.

Applicative programming is a simple but powerful way to transform lists or collections of any kind. An example of applicative programming is to find the square of every element of a list. For example, the list (0 1 2 4) becomes (0 1 4 16).

Natively, JavaScript applies Applicative Programming paradigms by providing some native array and string methods, all of which accept function values to be applied to each element/character of an array or string.

Applicative programming in JavaScript is possible because JavaScript has first class functions. This means that JavaScript functions can be assigned to variables, passed as arguments to other functions, and returned from functions just like numeric values.

A programing language has first-class functions if it can do the following

  • Use functions as return values of other functions
  • Use functions as arguments to other functions
  • Store functions in collections
  • Create new functions from preexisting functions at run-time

The native JavaScript functions for doing applicative programming  include 8 array methods (forEach(), every(), some(), filter(), map(), reduce(), reduceRight(), sort()) and one string method (i.e. replace()). A summary of their operations is described below:

  • [].forEach()– Executes a provided function once per array element
  • [].every()– Tests whether all elements in the array pass the test implemented by the provided function
  • [].filter()– Creates a new array with all elements that pass the test implemented by the provided function
  • [].map()– Creates a new array with the results of calling a provided function on every element in this array.
  • [].some()– Tests whether some element in the array passes the test implemented by the provided function
  • [].reduce()– Apply a function simultaneously against two values of an array (from left-to-right) as to reduce it to a single value
  • [].reduceRight()– Apply a function simultaneously against two values of an array (from right-to-left) as to reduce it to a single value
  • [].sort()– Optionally accepts a function that defines the sort order
  • “”.replace()– Optionally takes a function which passes the matches to the function

Underscore.js

Underscore.js, as described on their website, is “a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.”

Underscore allows you to drastically transform your arrays, objects, and functions with only a line or three of code, making it one of the most useful JavaScript libraries in a programmer’s repetoire.

Underscore.js is self-contained, and has no external dependencies; it provides every native function as part of a global _ object (e.g. _.map()).

Most importantly, it provides many additions and improvements for operating on collections (i.e. an array, object, or string), Object’s, and Array’s with function arguments.

Underscore provides additional functions/utilities for:

  • Templating
  • Wrapping collections, arrays, and objects so method chaining can be done (Think jQuery chaining and operating but not just on a list of DOM elements, rather on any sort of list/collection)
  • Solutions to deal with JavaScript Language Quirks (i.e.typeof abstractions)
  • Facilitating functional programming paradigms and patterns (e.g.curry, memoize,partial, compose)

Applicative Programming using Underscore

To highlight the power of Underscore in Applicative programming, we outline a few of the methods it provides for operating on Collections. For full coverage for Collections and others, visit the Underscore website http://underscorejs.org

Collections (i.e. Arrays or Objects)

Method (includes all aliases)

**Callback** Arguments

Description

Returns

_.all, _.every

_.every(list, [predicate], [context]) 

Returns true if all the values in the list pass the predicate truth test. Delegates to the native method every, if present.

Boolean

_.some, _.any

_.some(list, [predicate], [context]) 

Returns true if any value in the list pass the predicate truth test. Delegates to the native method some, if present.

Boolean

_.map, _.collect

_.map(list, iterator, [context])

Produces a new array of values by mapping each value in list through a transformation function (iterator). If the native map method exists, it will be used instead.

New Array

_.filter, _.select

_.filter(list, predicate, [context])

Looks through each value in the list, returning an array of all the values that pass a truth test (predicate). Delegates to the native filter method, if it exists.

New Array

_.forEach, _.each

_.each(list, iterator, [context]) 

Iterates over a list of elements, yielding each in turn to an iterator function. 

Collection Passed In

_.reduceRight, _.foldr

_.reduceRight(list, iterator, memo, [context])

The right-associative version of reduce. Delegates to the JavaScript 1.8 version ofreduceRight, if it exists.

The Accumulated Value

_.reduce, _.foldl, _.inject

_.reduce(list, iterator, memo, [context])

Also known as inject and foldlreduce boils down a list of values into a single value.Memo is the initial state of the reduction, and each successive step of it should be returned by iterator

The Accumulated Value

Applicative programming extends the understanding of JavaScript and all its nuances, and is a paradigm a JavaScript programmer is encouraged to understand.

Regards

The HackReactor Edge::Imparted to Impart Others || Taught to Teach Others

Week Four is just underway, and it begins with an introduction to the amazing opensource JavaScript framework by Google – AngularJS. We are in a deep-dive, and the bottom doesn’t seem near.

Week Three was just wrapped up, with in-depth coverage of Backbone (another JavaScript MVC) and CoffeeScript (JavaScript on steroids). Concepts like  Asynchronous Module Definition (AMD) to help you better organise your code; and powerhouses like Gulp.js (for automating your build system) ramp up your workflow as a developer by multiple orders of magnitude.

The curriculum just gets better and better.

Most awesomely: HackReactor did a piece about me on their blog!!! Mind-blowing awesomeness. There again is that spirit of community you get to experience with the HackReactor Edge. See the link below: 

http://www.hackreactor.com/blog/remote-student-chibueze-ukaegbu-using-hack-reactor-education-to-start-javascript-focused-school-in-nigeria

What’s else can I tell you? Come along, and get the HackReactor Edge.

 

Regards

Chibueze I.

 

 

 

 

Understanding Backbone Events System

Backbone uses a pub/sub event system to manage notifications for actions. A pub-sub system has 3 main components:

  • A place to store the things that happen when we trigger the event – internal implementaion
  • The method that broadcasts the event – Publish (trigger)
  • A system that allows us to register (for/to that) interest on that event – Subscribe (on)

A pub-sub system is an implementation of the Observer pattern and it helps in code decoupling; it makes it possible for components to publish or subscribe to different events based on the state of the system.

The general idea behind the Observer pattern is the promotion of loose coupling (or decoupling as it’s also referred as). Rather than single objects calling on the methods of other objects, an object instead subscribes to a specific task or activity of another object and is notified when it occurs. Observers are also called Subscribers and we refer to the object being observed as the Publisher (or the subject). Publishers notify subscribers when events occur.” …Addy Osmani

Backbone.Events Overview

The Backbone.Events object contains methods that facilitate the Observer design pattern and a variation of the observer pattern called pub/sub. These functions permit plain vanilla JavaScript objects or the various objects created by Backbone to communicate with each other in a decoupled manner.
To achieve this, the prototypes of the high-level constructor functions provided by Backbone are all extended with the functions contained in Backbone.Events (using the ubiquitous _.extend(Model.prototype, Backbone.Events) of Underscore fame). The affected constructors include:

  • Backbone.Model()
  • Backbone.Collection()
  • Backbone.View()
  • Backbone.Router()
  • Backbone.History()

To facilitate the pub/sub pattern, the Backbone.Events object contains the following functions which provide the functionality needed to create events, trigger events, and create listening relationships between objects based on events.

  • on(event, callback, context) aka bind()
  • off(event, callback, context) aka unbind()
  • trigger(event, arguments)
  • once(event, callback, context)
  • listenTo(other object, event, callback)
  • stopListening(other object, event, callback)
  • listenToOnce(other object, event, callback)

Binding Events to Objects using on()
The on() method will bind a callback function to an object, and that callback will be invoked whenever the event is triggered. The on() also accepts a string event parameter which can contain multiple events separated by a space. on() takes 3 arguments (the 3rd is optional): the name of the event(s), the callback function to execute when the event is triggered and the this context for the callback function.

 var ourObject = {};
 // Mixin
 _.extend(ourObject, Backbone.Events);

 // Add a custom event
 ourObject.on('dance', function(msg){
    console.log('We triggered ' + msg);
 });

 // Trigger the custom event
 ourObject.trigger('dance', 'our event');

on() provides the Subscribe mechanism.

Triggering And Passing Values To A Callback Function Using trigger()
The trigger() method is used to invoke named (i.e. events) callback functions. Its takes 2 parameters: the first is the name of the event(s) as a string; while the second parameter gives the option of passing values to the callback function.

 var ourObject = {};
 // Mixin
 _.extend(ourObject, Backbone.Events);

 function doAction (msg) { console.log("We are " + msg); }

 // Add event listeners
 ourObject.on("dance", doAction);
 ourObject.on("jump", doAction);

 // Single event
 ourObject.trigger("dance", 'just dancing.');

 // Multiple events
 ourObject.trigger("dance jump", 'very tired from so much action.');

trigger() provides the Publish mechanism.

Removing Events and Callback Functions with off()
The off() method can be used to remove previously bound events and callback functions from an object. The basic syntax takes the name of the event and the callback to remove as parameters; but calling off() with no parameters on a Backbone model, collection, view, or router object will remove everything including the built in BackBone events and callbacks.

var ourObject = {};
 // Mixin
 _.extend(ourObject, Backbone.Events);

 function dancing (msg) { console.log("We " + msg); }

 // Add namespaced custom events
 ourObject.on("dance:tap", dancing);

 // Trigger the custom events. Each will be caught and acted upon.
 ourObject.trigger("dance:tap", "started tap dancing. Yeah!");

 // Removes event bound to the object
 ourObject.off("dance:tap");

 // Trigger the custom events again
 // won't be logged as it's not listened for
 ourObject.trigger("dance:tap", "stopped tap dancing.");

Have an object listen for events on another object using listenTo()
The listenTo() method gives the ability for one object to listen for an event on another object, and when that event occurs provide a callback function that is invoked. listenTo() is called on the subscribing object (i.e the object to be notified when an event occurs) and it takes 3 parameters: the source object or publisher, the event type to listen for (as a string) and a callback function to execute when the event is triggered.

Stop listening for events on another object using stopListening()
The stopListening() method can be used on objects that are listening to other objects to terminate the notifications. Depending on the parameter passed in when the function is called, stopListening() can stop listening to a specific event, all events or all/specific events associated with an object.

 var a = _.extend({}, Backbone.Events);
 var b = _.extend({}, Backbone.Events);
 var c = _.extend({}, Backbone.Events);

// add listeners to A for events on B and C
 a.listenTo(b, 'anything', function(event){ console.log("anything happened"); });
 a.listenTo(c, 'everything', function(event){ console.log("everything happened"); });

// trigger an event
 b.trigger('anything'); // logs: anything happened

// stop listening
 a.stopListening();

// A does not receive these events
 b.trigger('anything');
 c.trigger('everything');

For a more comprehensive look at Backbone and Events, see the excellent article by Cody Lindley at http://tech.pro/tutorial/1367/part-1-backbonejs-deconstructed

Understanding Time Complexity

Understanding complexity theory will help you have a firmer grasp of algorithm design and execution.

To help our understanding, let us first define some terms.

An Algorithm can be defined as a program or sequence of steps to perform a desired task or computation.

Complexity Analysis is a tool that helps us examine how an algorithm behaves as its given inputs grow larger. It explains pertinent questions like: How would my algorithm behave if given an entirely different set of inputs? Will it run faster, half as fast or slower if I double its input size?

Worst-case Analysis refers to the process where we often consider the worst-case scenario when analyzing algorithms. It deals with answering questions like: What’s the worst that can happen for our algorithm? When does our algorithm need the most instructions to complete?

Combining the ideas of Complexity analysis and Worst-case anaylsis helps us measure how our algorithm will behave when stress-tested, treated badly or challenged to do something hard.

Big O Notation is a term used in Computer Science to describe the complexity and performance of an algorithm. It specifically performs worst-case analysis, describing the worst-case scenario for our algorithm in terms of execution time.

There are several orders of growth described by the Big O Notation, but in this article, we shall focus on 4 common ones.

A. O(1) – Constant time complexity: here, the time required to execute an algorithm is the same, regardless of the size of the input. For example, an algorithm to check the first item in an array will always execute in the same time whether the input array has 1 or 1,000 items.

function findFirstItem(array)
 {
     return array[0];
 }

B. O(N) – Linear time complexity: here, the performance of an algorithm will grow linearly in direct proportion to the size of the input data set. For example, iterating over an array to find an item. The uncertainty of the location of the item (beginning, middle or end) will affect time of search, as searching through an array of 1000 items will take longer than that of 50 items.

function findItemInArray(array, item)
 {
   var found = false;
   for (var index = 0; index < array.length; index++ )
   {
      if ( array[index] === item ){
         found = true;
         return found;
      }
   }   
   return found;
 }

C. O(N^2) – Quadratic time complexity: here, they performance of an algorithm is directly proportional to the square of the input data set. This is the scenario with algorithms that involve nested iterations over the same dataset. The simple example below tests if an array contains a duplicate value and returns true on the first instance.

function containsDuplicate(array)
{
   var isDuplicate = false;
   for ( var index = 0; index < array.length; index++ )
   {
      for ( var innerIndex = 0; innerIndex < array.length; innerIndex++ )
      {
         if ( index === innerIndex ) continue; //don't compare with self
         if ( array[index] === array[innerIndex] ){
            isDuplicate = true;
            return isDuplicate;
         }
      }
   }
   return isDuplicate;
}

D. O(log N) – Logarithmic time complexity: here, algorithms have a growth curve that peaks at the beginning and slowly flattens out as the size of the data set increases. For example in a binary search algorithm, doubling the size of the input has little effect on its growth as after a single iteration, the data set will be halved, and thus on par with an input data set half the size.

function binarySearch(items, value)
{
   var startIndex = 0,
   stopIndex = items.length - 1,
   middle = Math.floor((stopIndex + startIndex)/2);

   while(items[middle] != value && startIndex < stopIndex)
   {
      //adjust search area
      if (value < items[middle])
      {
         startIndex = middle + 1;
      }
      else if (value > items[middle])
      {
         startIndex = middle + 1;
      }
      //recalculate middle 
      middle = Math.floor((stopIndex + startIndex)/2); 
   } 
   //make sure it's the right value 
   return (items[middle] != value) ? -1 : middle; 
}

Understanding time complexity will make us better engineers, as it empowers us to craft the most efficient algorithms when solving problems.

Happy coding.