Afshin Mehrabani

Programmer, open-source lover. Creator of IntroJS, PACKT publishing author and technical editor.

Read this first

Using `object` as the keys of another `object` in JavaScript

Sometimes you need to use objects for the keys of a dictionary (let’s say, another object).

Assume this code:

var keys = [{a: 1}, {a: 2}, {a: 3}]; var dic = {}; //add a new key to the dictionary dic[keys[0]] = 'boo'; dic[keys[1]] = 'foo'; 

Above code yields this result:

console.log(dic); //Object {[object Object]: "foo"} 

So the dictionary doesn’t have two items because object keys cannot be object. You can get the item with [object Object] string:

console.log(dic['[object Object]']); //returns `foo` 

Ok, wait. Then how we can set objects as the keys of a dictionary?

ECMAScript 6 - Map

Map feature in ES6 enables you to assign objects as the keys of a dictionary (or another object).

Here is the ES6 compatible of the previous example:

var keys = [{a: 1}, {a: 2}, {a: 3}]; var map = new Map(); //add a new key to the dictionary map.set(keys[0], 'boo'); map.set(keys[1], 'foo'); 

And the ...

Continue reading →


Block scope variable - ECMAScript 6

Since some of ECMAScript 6 features looks weird to old-fashioned JavaScripters, I’m going to write a series of blog posts to describe the main idea of some common ECMAScript 6 features.

In this posts I’d like to explain the usage of block scope variables. The keyword let enables you to create a block scope variable in ECMAScript 6:

let boo = 1; 

So, what’s the difference between var boo = 1; and let boo = 1;? Assume following example:

function sample() { if (true) { var boo = 1; } return boo; } console.log(sample()); //returns 1 

In the above old-fashioned code, boo variable is defined within the sample function scope so we have the value even outside of the if statement.

With let variable you can create a variable that is available within the if statement block:

function sample() { if (true) { let boo = 1; } return boo; //ReferenceError: boo is not defined } console.log(sample()); 
...

Continue reading →


Python: List and Tuple performance benchmark

Suppose you have two options to implement a solution using a programming language, what are important factors to select one of options? I do believe one of concerns for a programmer would be performance benchmark between those options.

In this short blog post I’d like to share my simple code and results for performance benchmark between Python list and tuple. Two features to create a list, but with this difference, that tuples are immutable and you can’t alter them after initializing.

Following code shows a simple usage of list and tuple to create a series of items:

# this is a list, you can alter it in next lines l = [1, 2, 3, 4, 5] # this is a tuple and it's immutable t = (1, 2, 3, 4, 5) 

Please note that you can store different data types as an item for both tuple and list.

My scenario to make a performance benchmark between list and tuple is retrieving 2,000,000 random items from...

Continue reading →


Using Redis as session store for ExpressJS + PassportJS settings

Since all other articles about using Redis as a session store for ExpressJS are out of date due to latest update of connect-redis, I’m going to write this short article to show how to use Redis as session store for ExpressJS.

In order to use Redis as session store for ExpressJS, first of all install connect-redis package using npm:

npm install connect-redis 

Then, add connect-redis to your dependencies and Following code shows the content of app.js file:

var express = require('express'); var RedisStore = require('connect-redis')(express.session); app.use(express.session({ store: new RedisStore({ host: '127.0.0.1', port: 6379 }), secret: 'hey you' })); 

If you’re using PassportJS for users authentication, you can simply add two following lines to your app.js file to enable PassportJS as well:

app.use(passport.initialize()); app.use(passport.session()); 

That’s it. Now you have...

Continue reading →


Why C# is not a good choice for web development?

C# is the main programming language in Iran. I’ve worked with several teams, various projects and developers with different development skills. Earlier I’ve worked with PHP.

There weren’t any motivations to migrate from PHP to C# but the company’s infrastructure. Most of web development companies in Iran work with C# and Microsoft technologies, and here is the reason, because they don’t want to learn more. Companies prefer to stay at the same level and do not pay for improving their developers skills!

If you ask them: “Why you are using C# for web development?” I bet they won’t give you acceptable answer.

I haven’t used C# for my own projects, and I won’t at all. It’s preferable to me to use NodeJS or Python, not only because of their popularity, but because they are scripting languages.

After spending ages with C#-based web apps I want to tell something horrible about this language...

Continue reading →


How to fix `setImmediate is not defined` error in NodeJs

The setImmediate function introduced in NodeJS v0.10.x to queue functions. It works like process.nextTick function but with a difference in functionality. Read JohnnyHK’s answer to figure out: http://stackoverflow.com/a/15349865/375966

Most of the time, by upgrading the NodeJS core to v0.10.x it can simply solve your problem.

tldr; Upgrade your NodeJS to v0.10.x.

Continue reading →


Become a CreateJS Ninja with “Getting Started with CreateJS” book

Nowadays using HTML5 technologies to develop web pages are become more commonplace and consequently HTML5-based libraries are become more popular. CreateJS is one of popular and successful libraries for creating rich HTML5-based web pages.

What is CreateJS?

A suite of Javascript libraries & tools for building rich, interactive experiences with HTML5.

CreateJS consist of four different libraries and each one is responsible for specific part of HTML5 technology.

  • EaselJS
  • TweenJS
  • PreloadJS
  • SoundJS

With combination of all parts you can develop a rich web application easily.

Getting Started with CreateJS

If you want to start learning CreateJS as fast as possible, “Getting Started with CreateJS” book with Packt Publishing is a good starting point. It’s a step-by-step tutorial for all CreateJS subsets. The book consists of many practical examples that help you to learn faster.

Getting Started with CreateJS - Cover.jpg

If...

Continue reading →


MongoDB singleton connection in NodeJs

In this post, I want to share a piece of useful source code to make a singleton connection in NodeJs. By using this piece of code, you will have always one connection in your NodeJs application, so it will be more faster. Also, if you are using NodeJs frameworks like ExpressJs, it will be useful too.

connection.js:

var Db = require('mongodb').Db; var Connection = require('mongodb').Connection; var Server = require('mongodb').Server; //the MongoDB connection var connectionInstance; module.exports = function(callback) { //if already we have a connection, don't connect to database again if (connectionInstance) { callback(connectionInstance); return; } var db = new Db('your-db', new Server("127.0.0.1", Connection.DEFAULT_PORT, { auto_reconnect: true })); db.open(function(error, databaseConnection) { if (error) throw new Error(error); connectionInstance = databaseConnection;...

Continue reading →


Simplified MapReduce

I believe one of the best solutions to solve a programming problem is to find a paper or article and read it as a clue. Well, of course Wikipedia, BMI and other sources are really helpful but somehow reading them is a nightmare for me, because of complexity of explanation. Thus, It’s preferable for me to read a straightforward article to find the clue.

You have a problem you find a paper about it. Now you have one and a half problems. Understanding the paper, and implementing it.

— Amir Mohammad Saied (@gluegadget) February 6, 2014

And now, I want to straightforwardly describe one of usable algorithms, its called MapReduce. Perhaps you have heard that before in Hadoop, MongoDB or NoSQL discussions.

Here is an introduction to what is a MapReduce is:

MapReduce is a programming model for processing large data sets with a parallel, distributed algorithm on a cluster.

From:...

Continue reading →


Programming languages war

So frequently I hear a tedious conversation between my colleagues, “PHP is better than foo”, “.NET is better than boo” etc. etc. Each time I hear this sort of dialog I try to ask the reasons of this comparison but till now, no one has given a proper answer since somehow it’s impossible.

Up till now, I’ve coded with JavaScript, PHP, C# and little bit Python. I’m still a newbie in programming industry, but at least I had a lot of mutual projects with some experts. The result of being a part of those projects, taught me how to tackle a problem, how to choose an adequate tools or language and prepare the environment to solve it. Almost in all cases, indicating the programming language wasn’t the bottleneck. However, we did that with considering the problem’s parameters. Design a good architecture and implementing it correctly was the main goal in our projects.

I’d like to point it that...

Continue reading →