jQuery slider for horizontal images scrolling

This is totally haphazard post, was created during the absolute idleness.
I believe that everyone saw this “trick” many times – horisontal slider scrolls horizontal line of images.
Here is simple markup

<div class="scrollableContainer">
    <div class="content">
        <div class="scrollableContent">
            <div class="item">1</div>
            <div class="item">2</div>
            <div class="item">3</div>
            <div class="item">4</div>
            <div class="item">5</div>
            <div class="item">6</div>
            <div class="item">7</div>
            <div class="item">8</div>
            <div class="item">9</div>
            <div class="item">10</div>
        </div>
    </div>
    <div class="slider"></div>
</div>
<div class='console'></div>

we gonna use numbers instead of images (imagine that these numbers are images for the poor)

some styles:

.scrollableContainer {
    width: 500px;
    height: 200px;
}
.scrollableContainer .content {
    border: 2px solid #999;
    border-radius: 5px;
    height: 100px;
    width: 500px;
    overflow: hidden;
}
.scrollableContainer .scrollableContent {
    font-size: 30px;
    margin-left: 0px;
    width: 1000px;
}
.scrollableContainer .scrollableContent .item {
    font-size: 50px;
    font-weight: bold;
    border: 5px solid grey;
    border-radius: 5px;
    width: 70px;
    height: 70px;
    margin: 10px;
    text-align: center;
    float: left;
}
.scrollableContainer .slider {
    width: 300px;
    margin-top: 20px;
    margin-left: auto;
    margin-right: auto;
}
 
/* overridings for jquery UI styles: */
.scrollableContainer .slider .ui-slider-handle.ui-state-default.ui-corner-all {
    border: 4px solid #999;
    border-radius: 50%;
    cursor: pointer;
}
 
.scrollableContainer .slider.ui-slider.ui-slider-horizontal.ui-widget.ui-widget-content {
    background: #ddd;
}

and here is the magic:

$(function() {
    $( ".slider" ).slider({
        slide: function( event, ui ) {
            $('.console').text(ui.value);
            $('.scrollableContent').css('margin-left', -ui.value * 4);
        }
    });
});

How it works – div with width 1000 px is inside of the div with smaller fixed width and “overflow: hidden”, and we just need to change “margin-left: -X” of the internal div depending on the slider’s position.

Here is my fiddle http://jsfiddle.net/TGEQf/

Social Share Toolbar

How to clone an object in JavaScript

What is the most efficient way to clone an object in JavaScript?

Here is the wrong way that will not work properly

var obj1 = { a: 1, b: { c: {d: 2}, e: 3}},
	obj2 = {};
 
console.dir(obj1);
 
for(var key in obj1) {
	if(obj1.hasOwnProperty(key)) {
		obj2[key] = obj1[key];
	}
}
 
console.dir(obj2); // seems the same object, but NOT

obj2 will look the same as an obj1, but it’s not a clone (because we just copied references), let’s prove that:

var obj1 = { a: 1, b: { c: {d: 2}, e: 3}},
	obj2 = {};
 
for(var key in obj1) {
	if(obj1.hasOwnProperty(key)) {
		obj2[key] = obj1[key];
	}
}
 
obj1.b.c.d = 42; // Changed obj1
 
console.dir(obj2); // OOPS, changes of obj1 has been applied to obj2

So it’s not a clone.

Here is the most efficient “handmade” way to clone the object:

var obj1 = { a: 1, b: { c: {d: 2}, e: 3}},
	obj2 = {};
 
obj2 = JSON.parse(JSON.stringify(obj1));
 
obj1.b.c.d = 42; // Changed obj1
 
console.log(obj1);
console.dir(obj2); // cool, obj2 still the same

BTW, in production code it’s recommended to use this way:

var obj1 = { a: 1, b: { c: {d: 2}, e: 3}},
	obj2 = {};
 
obj2 = $.extend(true, {}, obj1); // jQuery extend method
 
obj1.b.c.d = 42; // Changed obj1
 
console.log(obj1);
console.dir(obj2); // cool, obj2 still the same

I think that it is the best way to clone the object (described above)
Here is the list of all possible ways to clone the object:

// jQuery deep copy:
var newObject = jQuery.extend(true, {}, oldObject); // 76% slower
// JSON
var newObject = JSON.parse(JSON.stringify(oldObject)); // 12% slower
// jQuery copy (not deep)
var newObject = jQuery.extend({}, oldObject); // 24% slower
// simple clone function
var newObject = clone(oldObject); // fastest way, first function, that will copy only references (seems to be completely wrong way)
// ES5 Object.clone
var newObject = Object.clone(oldObject); // 85% slower

Here is the link on benchmark http://jsperf.com/cloning-an-object/2

So, the best production way to clone the object is still jQuery deep copy (not due to the benchmarks, but it’s the most safe and recommended way)
Let’s dig into this, and take a look under the hood. Here it the source code of jQuery extend:
https://github.com/jquery/jquery/blob/master/src/core.js#L265

Here is the “core” part

	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];
 
				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}
 
				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray(src) ? src : [];
 
					} else {
						clone = src && jQuery.isPlainObject(src) ? src : {};
					}
 
					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );
 
				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

So, let’s take a look at fully “handmade” function “clone”
Here is simplified similar function (but not the same)

function extend (target, other) {
  target = target || {};
  for (var prop in other) {
    if (typeof source[prop] === 'object') {
      target[prop] = extend(target[prop], source[prop]);
    } else {
      target[prop] = source[prop];
    }
  }
  return target;
}

P.S.
somewhere I saw this way to clone the object

eval(uneval(o));

Please, do not even think about using of this. Eval is completely evil (Douglas Crockford will help you to find out the reason)

Social Share Toolbar

How to use mongoose with MongoDB in Node.js

Here is the example how to start simple project with usage of Mongoose for MongoDB on Node.js and mongoDB hosted on mongolab.

First of all you need to correct package.json file in your project to something like this

{
    "name": "rent",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node app"
    },
    "dependencies": {
        "express": "3.0.2",
        "jade": "*",
        "log4js": "0.5.6",
        "mongoose" : "3.5.4",
        "moment" : "1.7.2",
        "mongoose-pureautoinc": "*"
    }
}

Make sure that you have added mongoose package, other stuff just for example
run
Mikitas-MacBook-Air-2:test nik$ sudo npm install
or just “npm install” (for windows or if you configured permissions)
You can also use “npm install mongoose” to install it.

Let’s create mongoDB “model”. So somewhere in your DAL try this code:

var mongoose = require('mongoose')
    , Schema = mongoose.Schema
    , ObjectId = Schema.ObjectId;
 
// let's create scheme for some random stuff:
var postSchema = new Schema({
    _id: ObjectId,
    thumbnail: String,
    whenCreated: Date,
    whenUpdated: Date,
    comments: [{
            author: {
                authorId: ObjectId, 
                name: String, 
                thumbnail: String
            }, 
            date: String, 
            text: String
    }],
    rating: Number,
    isApproved: Boolean,
    text: String
}, { collection: 'post'});
 
// and let's register this scheme as a model and make global for this module
module.exports = mongoose.model('Post', postSchema);

Now we can include this file:

var Post = require('../DAL/models/Post');

And use it for example to get all items from collections

exports.getPosts = function (callback){
	return Post.find({/* query */}, function (err, docs){
		if (!err) { 
			callback(docs);
		}
		else { 
			throw err;
		}
	});
}

Note: that the operation is async and you will get result only in callback
please check this mongo docs out

Or we can insert new item into collection:

exports.addPost = function (){
    var post = new Post();
    post.rating = 5.89;
    post.text = "Here is one more post to my blog on MikitaManko.com/blog/"; 
    post.isApproved = true;
    // other fields
    post.save();
}

Here is one more link on mongo docs

Finally, to use this “DAL” methods we need to create connection to DB.
You can use https://mongolab.com/ service to host your DB for free (until your DB is less then 500 mb).
After you created new BD on mongolab you can create connection with the following way:

var mongoose = require('mongoose');
 
mongoose.connect('mongodb://<your login>:<your password>@<your id>.mongolab.com:61777/<database name>');
// here you can call methods described above

That’s it, just several lines of code, some clicks and you have MondoDB database already hosted in web.
Perfect solution for Hackathons, fast tests and startups.

By the way, you can host you Node.js code on https://www.heroku.com/ service also for free (until it exceeds some limitation, for details check heroku website out)

Social Share Toolbar

JavaScript Quiz

Some awkward questions that may be asked on the interview or during the JavaScript lectures.

Type conversion

var a = 1 + '2' + 3;

Answer:

“123” because 1 will be converted to string and “1” + “2” is strings concatenation operation

var b = +(1 + 2 + '3' + 4) + 5;

Answer:

“339” similar situation, firstly 1 and 2 will be summarized as numbers, and the result will be 3. Then conversion to string and will be concatenated “34”. After that the string “334” will be converted to the number, because of plus operator. Afterwards to the number 334 will be added 5, so the result is 339

var c = '4' - 3;

Answer:

1, because the second operand is integer, so the first one will be converted to number 4

Context

if (!("a" in window)) {
    var a = 1;
}
alert(a);

Answer:

undefined. Because:

1) all global variables are properties of window. Writing var a = 1 is functionally equivalent to writing window.a = 1

2) all variable declarations are hoisted to the top of the containing scope.

variables vs functions hoisting

var a = 1,
b = function a(x) {
    x && a(--x);
};
alert(a);

Answer:

1
Because:
1) variable declaration hoisting (where declaration is “var a;” and initialization is “a = 1;”)
2) All function declarations are hoisted to the top of the containing scope along with variable declarations. Function expressions are not hoisted.
where declaration is “function functionName(arg1, arg2) { /* function declaration – will be hoisted */ }”
and expression is “var functionName = function (arg1, arg2) {/* function expression */};”
Problem? Just read ECMA 5 (13.0)
3) function declarations override variable declarations but not variable initializations. The variable initialization overrides the function declaration.
So
function value() {
return 1;
}
var value;
alert(typeof value); //”function”

and

function value() {
return 1;
}
var value = 1;
alert(typeof value); //”number”

one more variables vs functions

function a(x) {
    return x * 2;
}
var a;
alert(a);

Answer:

the answer is the body of function a:
function a(x) {
return x * 2;
}
Ha-ha, function declarations override variable declarations unless there’s an initialization.
So, for this case
function a(x) {
return x * 2;
}
var a = 1;
alert(a);

we gonna get – 1
Pretty cool, yep?)

arguments

function b(x, y, a) {
    arguments[2] = 10;
    alert(a);
}
b(1, 2, 3);

Answer:

10
Because each entry in the arguments object is a duplicate of each named argument.

context

function a() {
    alert(this);
}
a.call(null);

Answer:

[object Window]
Reasons are:
1) When a method is called on an object, this points to the object on which the method resides.
2) If thisArg is null or undefined, the called function is passed the global object as the this value. Otherwise, the called function is passed ToObject(thisArg) as the this value. (in this case it will be window)
So, the code above could be converted to:
function a() {
alert(this);
}
a.call(window);

Or, even to

alert(window);

typeof

typeof typeof (null)

Answer:

“string”
Firstly typeof operator always returns a string value (in this case, it returns “object” for typeof(null)). null is type object and undefined is type undefined.
Whenever you have typeof typeof, the result is always “string”.

toString

100['toString']['length']

Answer:

1
1) Numbers end up wrapped by the Number type when you use them, and the Number type has a toString()
2) The length property of a function indicates how many names arguments are expected. The toString()methods accepts one argument, which is the radix in which to output the string representation of the number (for example toString(2) outputs the binary representation of the number as a string and toString(16) outputs the hexadecimal representation of the number as a string).

Comma

var a = (1, 5 - 1) * 2;

Answer:

8
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand (not the second, the last one)
Some extra examples:
a = ‘hello’, ‘world’; //’world’
a = 1, 2 + 3, 4 – 1; //3

One more comma

var x = 10;
var foo = {
    x: 20,
    bar: function () {
        var x = 30;
        return this.x;
    }
};
console.log(
  foo.bar(), // 1 case
  (foo.bar)(), // 2 case
  (foo.bar = foo.bar)(), // 3 case
  (foo.bar, foo.bar)() // 4 case
);

Answer:

1 case – 20
2 case – 20
3 case – 10
4 case – 10
Brain damage… ?
That’s pretty simple in case if you bear in mind that foo.bar in this part of the code represents a pointer to the function, and the comma operator takes on the value of that function before being called. 
Also, for case 3 function location gonna be changed to window.

Arguments

function f(x, y) {
    x = 10;
    console.log(arguments[0],
        arguments[1]);
}
f();

Answer:

undefined undefined
The arguments object and the named argument do not share memory space. When a change is made to arguments, that value is copied to the named argument. It doesn’t work the other way.
A named argument is no more special than a local variable, and so changing its value doesn’t affect the arguments object.

P.S. If you were able to solve all these quizzes, my congratulation you are cool enough! Just mail me to gmail(doggy)MikitaManko.com and I will recommend you if needed =)

Social Share Toolbar

JavaScript design patterns

Here are the most common JavaScript solutions that should be used in production code, everybody calls this list as JavaScript Design Patterns, but I think that it’s just good code’s rules. By the way, here they are:

immediate function pattern
purpose: to wrap some code in the context. Let us reduce polluting of the global context

(function () {
    alert('Hello');
} ());

purpose: the same solution, but with saving of results

var someVar = (function () {
    return 'result';
} ());

purpose: here is the real world example, it allows to use $ symbol as a jQuery in one context and as a Prototype library in another context without polluting of the global context. This solution must be used with any external library.

(function ($) {
    $(".menuOverlay").show();
} (jQuery || $));

note: Immediate function wrapped in parens, because:

  • Without parens it would be interpreted as function declaration (not expression) which is syntax error
  • Function expression can not start with word “function”

What is a Function Declaration?

function foo() {
    return 'result';
}

What is a Function Expression?

var bar = function () {
    return 'result';
}

immediate object initialization pattern
purpose: This pattern is mainly suitable for one-off tasks, and there’s no access to the object after the init() has completed. If you want to keep a reference to the object after it is done, you can easily achieve this by adding return this; at the end of init().

({
    width: 100,
    height: 200,
 
    getArea: function () {
        return this.width * this.height;
    },
    init: function () {
        console.log(this.getArea());
        //other init code
    }
}).init();

memoization pattern
purpose: the main goal is performance optimization. It’s real deal to save pre-calculated results. E.g. for Fibonacci numbers, juat implement solution with and without this pattern and you will see the difference.

function average(x, y) {
    var key = x + '_' + y;
    if (!average.cache.hasOwnProperty(key)) {
        average.cache[key] = (x + y) / 2;
    }
    return average.cache[key];
}
average.cache = {};
 
average(10, 20); //calculate
average(10, 20); //take from cache
average(20, 10); //calculate

Loop closure pattern
purpose: to eliminate “cycle f**k ups”, I mean the situation when you use cycle iterator variable in closure and you expect 1, 2, 3 .. values in different functions, but you have always last value in all.

var arr = ['one', 'two', 'three'];
 
for (var i = 0, len = arr.length; i < len; i++) {
    (function (i, d) {
        //access index and data
        console.log(i + ') ' + d);
    } (i, arr[i]));
}

The same code with jQuery

var arr = ['one', 'two', 'three'];
 
$.each(arr, function (i, d) {
    console.log(i + ') ' + d);
});

implementation is similar to

var forEach = function (d, f) {
    for (var i = 0, l = d.length; i < l; i++) {
        f(i, d[i]);
    }
};

Private member
purpose: restrict access to private members

function Semaphore(start) {
    var value = start; //private variable
 
    //private method
    function resetValue(){
        value = 0;
    }
 
    return {
        enter: function () {
            value++;
        },
        leave: function () {
            value--;
        },
        getValue: function(){
            return value;
        }
    };
}
 
var sem = new Semaphore(0);
sem.enter();
sem.enter();
Assert(sem.getValue()==2);
sem.leave()
Assert(sem.getValue()==1);
Assert(!sem.hasOwnProperty('resetValue'));//could not access private method
Assert(!sem.hasOwnProperty('value')); //could not access private variable

Optional parameter pattern

purpose: add ability to specify optional parameters
When function has a lot of parameters

function Car(name, model, color, number, wheelsRadius, year, autoTransmission) {
    //do something with all parameters
    return 'result';
}

This is bad code, because all parameters must be set when instantiating (even optional parameters)
e.g.

var myCar = new Car('Honda', 'civic', 'red', null, null, 2004, false);

also the order of the parameters is fixed and it’s hella hard to add one more parameter, when this is boilerplate code

So, the decision is to convert list of parameters to one object…

function Car(settings) {
    var defaultSettings = {
        name: 'Unknown',
        model: null,
        autoTransmission: false,
        wheelsRadius: 16
    };
 
    this.settings = $.extend({}, defaultSettings, settings);
 
    return this.settings;
}
 
var myCar = new Car({ name: 'Honda', model: 'civic', color: 'red', year: '2004', autoTransmission: true });

Note: if function has more then 3 parameters it must be converted to the function with one object-parameter.

Namespace pattern
purpose: reduce pollution of global context and simplify code organisation.
Here is Bad practice (pollute global scope):

function Init() { };
function Run() { };
var state = 1;
var module1 = {};
module1.data = [1, 2, 3];
var module2 = {};

Here is Better practice, but not good enough:

var MYAPP = {};//only one global object;
MYAPP.Init = function () { };
MYAPP.Run = function () { };
MYAPP.state = 1;
MYAPP.module1 = {};
MYAPP.module1.data = [1, 2, 3];
MYAPP.module2 = {};

Why not good enough? Because if you have a lot of modules, you will do something like:

if (typeof MYAPP === "undefined") {var MYAPP = {};}
if (typeof MYAPP.modules === "undefined") {var MYAPP.modules = {};}

Here is the Namespace pattern (read it carefully, it’s pretty interesting):

var MYAPP = MYAPP || {};
MYAPP.namespace = function (nameSpace) {
    var parts = nameSpace.split("."),
        parent = MYAPP,
        i;
 
    if (parts[0] === "MYAPP") { // strip redundant leading global
        parts = parts.slice(1);
    }
    for (i = 0; i < parts.length; i++) {
        // create a property if it doesn't exist
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};

To create new (or get already existing) namespace you need to write:

var moduleCar = MYAPP.namespace("MYAPP.modules.moduleCar");

Module pattern
purpose: Javascript doesn’t have special syntax for packages, but with help of “namespace” and “immediate function” patterns we can achieve this:

MYAPP.namespace("MYAPP.utilities.stack");
MYAPP.utilities.stack = (function () {
    var stack = [];
 
    function push(value) {
        stack.push(value);
    }
 
    function pop() {
        return stack.pop();
    }
 
    function somePrivateMethod() {
        stack = [];
    }
 
    return { // public API
        push: push,
        pop: pop
    };
} ());

Chaining pattern
purpose: add ability to use similar cool stuff as it possible with jQuery (I mean this chaining – $(‘.container’).html(markup).show() …)

var calculator = (function () {
    var value;
    return {
        init: function (startValue) {
            value = startValue;
            return this;
        },
        add: function (val) {
            value += val;
            return this;
        },
        mul: function (val) {
            value *= val;
            return this;
        },
        result: function () {
            return value;
        }
    };
} ());
 
console.log(calculator.init(2).add(2).mul(2).result());//8

P.S. It’s pretty obvious, but you can use different combination of these patterns to achieve your goal.

Social Share Toolbar