Module Pattern in Javascript

Lately wrote about Singleton Pattern in JavaScript after which thought of writing few lines about the famous module pattern.

As per the textbook definitions :

Module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language that does not support it, or only supports it, partially.

Putting it in a simple equation Creational Pattern + Structural Pattern => Module Pattern

String#each missing in ruby1.9

One might have noticed that String#each is no more present in ruby1.9

1.9.1 :002 > "hemanth".each
NoMethodError: undefined method `each' for "hemanth":String

Lately, was working on huge code base where, code had String#each assuming it will always get an array as ruby1.8 has String#each and also Array#each, but it does not get Strings at times so had to fix them.

With statements got better with python 3.1

In my previous post about using the with statement in python /me had tried to throw some light on why to use 'with' statements and the fun of using them.

Had also mentioned about, the contextlib module for python 2.7+ but with 3.X 'with statements' were better and the fun multiplied!

Cross-Window Messaging

Cross-origin/window communication is possible with the HTML5 API window.postMessage

Scripts on different pages are only allowed to access each only if the pages which executed them are at locations with the same protocol and host, but window.postMessage provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.

Before diving into some theory, have a look at the demo

Class handling with classList

classList returns a token list of the class attribute for a given element, with which one can do the below easily!

  • add a class to an element's list of classes

  • remove a class from an element's list of classes

  • toggle the existence of a class in an element's list of classes

  • check if an element's list of classes contains a specific class

asynchronous loading of css and javascript

Sometime back was pawing at async forEach in JavaScript that helped me to make a simple inject function that would help in loading CSS and JavaScript files to the HTML asynchronously!

async forEach in JavaScript

After writing about Blocking vs Non-Blocking /me was stuck with making forEach of JS asynchronous as it was very much needed for an interesting challenge.

As I was stuck with a broken callback function trying to make async, took help from one of my hacker friends Mortchek to come up with a async loop, as below :

Singleton Pattern in JavaScript

What is Singleton Pattern?

The singleton pattern is a design pattern that restricts the instantiation of a class to one object, much inspired from singleton set {0}.

Where is it useful?

  • Controlling concurrent access to a shared resource.

  • Abstract Factory implementation.

  • One time read variables. etc

Arrow functions in javascript

CoffeeScript is influencing javascript with fat arrows! As python had influenced it before with list comprehensions.

Well, the grammer looks like :

AssignmentExpression :
    ArrowFunctionExpression
    ...

ArrowFunctionExpression :
    ArrowFormalParameters => [lookahead ∉ { "{" }] AssignmentExpression
    ArrowFormalParameters => Block

ArrowFormalParameters :
    ( FormalParameterList_opt )
    Identifier

Getting home path and username in python

Getting home path and username in python, were just an one liners for me so for : os.path.expanduser("~/") and pwd.getpwuid(os.getuid())[0] were doing the job for me, but when a friend was stuck with doing the same for multiple platforms he was facing few issues, so played a bit with it and came up with some silly code that worked for him, thought it was wroth sharing the code snippet with you guys, hoping it will get better!

Parsing query string in javascript

Well there are hell lot of solution out there for parsing query strings in javascript, but still /me managed to make my own function!

params = (function () {
 
    res = {};
 
    window.location.search.replace("?","").split('&').map(
 
    function (q) {
        var v = q.split('=');
        res[v[0]] = v[1];
    });
 
    return res;
})();

Let's break it down!

HTML5 canvas full-screen and full-page

HTML5 canvas gets really complex for left brain oriented organisms!

This post tries to explain how to make a canvas element to occupy an entire page and also how to go full screen with canvas.

Even though the focus is mainly on full screen and full page canvas, the sample code demonstrates simple ways to create and color canvas.

Camera and Microphone Access with HTML5

Yes, Plugin-free acess to camera/microphone with HTML5!

Welcome to the post-flash revolution aka smartphone development. Flash isn't even available on Android 4.1.

AFAIK Ericsson labs were first to experiment on handling devices with HTML5, now with the  navigator.getUserMedia we can handle both camera and microphone devices with ease.

It's important to note that this works with Chrome 18.0.1009.0 with the --enable-media-stream flag set, Firefox nightly and Opera 12.

In chrome type 'chrome://flags' in your address bar. Find 'Enable MediaStream' and enable it.

Top 5 javascript oneliners

Javascript is once such beautiful language, where every thing can be minified to one line ;)

But in this post I have tired to collected five (most useful for me so far) javascript functions.

Using The 'with' statement in python

The "with" Statement PEP was created way back in 2005, PEP 343 to be precise, but /me notice many still coding with old syntax with is not bad, but does not look clean?!

So thought of making a small entry here, about using the with statement in python.

PEP 304 was originally written in first person by Guido, and subsequently updated by Nick Coghlan to reflect later discussion on python-dev. Any first person references are from Guido's original.

Iterating list or array with index

Iterating an array or a list with index while scripting, has it's own purpose.

Before we discuss about iterating an array or a list with index, let's list few of the common scenarios were this is useful :

  • Iterating through lines in a string and keeping track of line number.

  • Zipping two or more arrays into one.

  • If the index is a meaningful position (for example inserting objects in order into the database and updating their sort column etc).

  • Looping over a nested data-structure, say JSON with array elements.

Classes in JavaScript ES6

Well, well... there are so many JavaScript frameworks that already try to implement classes as per the classical Object Oriented Class definition.

But, with harmony (ES6) implementing classes like classical OO shall be possible.

This might be something like the IPv6 boom, most of the JavaScript hackers are used to making use of first class functions as classes and that shall remain along with this paradigm, is what I feel personally.

Blocking vs non-blocking in node.js

The most common task that any developer would do is File I/O, this being a very fundamental process :

  • Open a File.

  • Read it's contents and print.

  • Do something else.

Let's see how this can be done with blocking and non-blocking code in node.js and see how it matter!

RSS as JSON using node.js

Lately me and one my hacker buddies we talking about a project plan, in which RSS as JSON was a major module, some simple module mixing from node made the job very easy.

Made a npm package out of it, to install just do npm install rsj

Code for which, is very simple, yet seems to be doing the job as needed so far, the code looks like :

exports.r2j = r2j;
 
var FeedParser = require('feedparser');
parser = new FeedParser();
 
function r2j(uri, cb) {
  parser.parseUrl(uri, function (err, meta, articles) {
    if (err) return console.error(err);
    cb(JSON.stringify(articles));
  });
}

How caching matters in JS?

Caching plays a very important role, may it be on the client side or on the server side.

I tired to do a tittle benchmark test with benchmark.js and caching proved to benefit the performance remarkably.

To state the numbers, cache less query was 98% slower than the cached query!

It's Agreeable, that cache has it's on limitations on live objects, but it's worth a timely cache update in that case.

Globbing in scripting languages

Globbing is the most common and yet the most powerful operation that any scripter would use.

glob() is a Unix library function that expands file names using a pattern-matching notation reminiscent of regular expression syntax but without the expressive power of true regular expressions.

All most all the scripting languages has the globbing feature in them, yet here the mail focus in on bash, python, ruby, perl as they are my favs!

Inspecting Objects in Scripting

Examine the contents of a class / object is one of most useful and repetitive tasks that most of the coder do while debugging.

Here I try to focus on inspecting objects in scripting few of the major scripting languages that /me like.

Mainly JavaScript, Python, Ruby and Perl shall be covered in this article, feel free to suggest your ways to doing this.

Handling Internationalized domain name (IDN) in scripting

IDN is helping many, but caused a lot of trouble initially for many programming languages, specially in parsing and reading their contents.

The focus of this article is on scripting languages : bash, perl, python and ruby reading contents from an IDN or simply say an URL with unicode chars in them.

Google hourly hot trends on command line

Well, /me back to pawing at Google from CLI, after few silly apps like getting the weather, news, sunrise and sets from terminal from me, again tonight before I hit the bed, did a silly ruby code to get the hourly hot trends on the CLI.

Even though the page had CDATA in it, ignored it fully, rather took advantage of it with nokogiri in ruby to get them all.

All you have to do is install the nokogiri gem and then try the tiny little script presented below.

ES6 in node.js

Well first for thanks to paulmillr for his wonderful contribution of es6-shim for node.js and browsers.

As ECMAScript 6 drafts gets better each day, /me had an itch to try it before the browser wars will implement them on after the other, this itch led me to try it with node.js and trust me it's awesome!

Well as of today, FF13 is the first browser to introduce Sets and Maps API but we can try out the features in node.js right away.

Get iframe contents using queryselectors

With few security issues and hassles iframes has still managed to survive, the main reasons being :

  • iframes helps to beat the same origin policy and implements the cross domain origin policy.

  • iframes allows multiple types of resources not just certain mime-types.

May be  sandbox, srcdoc and  seamless will help many, also postMessage API!

But this article is not about explaining the good, bad and ugly of iframe, but its about selecting data from iframes!

What's the deal with on{X} ?

M$cro$fot has made a big move! is it a realisation that open source (rather free) software/platform is the way to go or it is some more microsofty?

/me tired to read between the code and has tired to crack the mystery behind on{x}

On{x} is a M$ online platform for automating android smart phones! Yes I said ANDROID

Reading logs made easy with bash.

Most of the web programmers would normally look into their applications/server error logs when they find issues, indeed it's a pain when the log path is filled with directories, it's sometimes annoying to do an ls -l and look for the latest directory and then cd it, a bit better case is when one tab_completes to change directories.

It would be very easy if we could cdn as in cd to the new dir ;)

So /me tired some silly script that would make my life easier, do add it to your ~/.bash.rc if we like it!

Sets and Maps in JavaScript

FF13 comes out with experimental support for ECMAScript 6 Map and Set objects.

As maps and sets can be easily implemented without this support, they have been introduced as experimental support

It's important to note :

An Object has a prototype, so there are default keys in the map. However, this can be bypassed using map = Object.create(null). The keys of an Object are Strings, where they can be any value for a Map. You can get the size of a Map easily while you have to manually keep track of size for an Object.

Ninja Object Properties in Scripting languages

10 hours ago, came across atrick-wied's ninja object properties in JavaScript, that speaks of code as below.

var x = {};
x[""] = 1;
x[" "] = 2;
x["  "] = 3;
 
console.log(x)
 
x= {}
 
x[String.fromCharCode(1)] = 1;
x[String.fromCharCode(2)] = 2;
x[String.fromCharCode(3)] = 3;
x[String.fromCharCode(4)] = 4;
 
console.log(x);

This is not very obfuscated JS-code, but indeed fun to see spaces as object properties and space as

On the same lines out of interest tried exploring the same property in other languages