## Bucket Sort algorithm in JavaScript

Bucket (bin) sort is a sorting algorithm that parts an array into buckets. Each of these are sorted recursively with the bucket sorting algorithm. The basic procedure of Bucket Sort is:
1. Create an empty array
2. Loop through the original array and put each object in a “bucket”
3. Sort each of the non-empty buckets
4. Check the buckets in order and then put all objects back into the original array

```var array = [2, 4, 1, 5, 3];
bucketSort(array);

function bucketSort(a) {
var r = [], b = [], v, c;
for (v of a) (b[v] || (b[v] = [])).push(v);
for (c of b) if (c != null) for each (v in c) r.push(v);
return r;
}```

For more information on the Bucket Sort check the Wikipedia page here: Bucket Sort – Wikipedia.org.

## Bubble Sort Algorithm in JavaScript

Bubble Sort is a very simple sorting algorithm. It works by stepping through a list to be sorted repeatedly while comparing each pair of coinsiding items and switching them if they are ordered incorrectly. This is a useful algorithm for doing simple comparisons in lists, but there are much more efficient algorithms for larger lists.

Bubble Sort example in JavaScript:

```    var numbers = [3,5,2,4,7,9,6,4,5];
var tmp;
for (var i = 0; i < numbers.length; i += 1) {
for (var j = i; j > 0; j -= 1) {
if (numbers[j] < numbers[j - 1]) {
tmp = numbers[j];
numbers[j] = numbers[j - 1];
numbers[j - 1] = tmp;
}
}
}
console.log(numbers);```

For more information on the Bubble Sort check the Wikipedia page here: Bubble Sort – Wikipedia.org.

## First Few Milliseconds of an HTTPS Connection

What actually happens behind the scenes of a HTTPS connection?

Client Hello. TLS wraps all traffic in “records” of different types. We see that the first byte out of our browser is the hex byte 0×16 = 22 which means that this is a “handshake” record.

The next two bytes are 0×0301 which indicate that this is a version 3.1 record which shows that TLS 1.0 is essentially SSL 3.1.

The handshake record is broken out into several messages. The first is our “Client Hello” message (0×01). There are a few important things here…..” (continued in full article link below)”

full article: The First Few Milliseconds of an HTTPS Connection

Tags: , , , , , ,

## Explanation of How Git Works

Git is a distributed version control and source code management system. It was created originally by Linus Torvalds, who also had developed the original Linux kernel. Git is one of the most popular version control systems in use today.

How does git really work behind the scenes?

Each git directory is a full repository that includes the entire history and versioning with no external dependencies (e.g. no central server). All of this git metadata is stored in a .git directory in the base of each repository directory.

Every git repository essentially consists of a simple key-value store in which all of the objects are indexed by SHA-1 hash values. These objects consist of all types of git data, including: tags, files, commits, etc. This storage unit is the object database. There are essentially 4 specific types of objects: blob (files), tree (directories), commit (links trees together to form a history), and tag (container that contains references to other objects and meta data).

In addition to the object database, git has another data structure. The other data structure is a mutable index that is used to cache information about the repository directory and the current revision that has yet to be committed.

When objects are added they are hashed and then referred to by the SHA-1 hash value. Git first computes this hash (used for object’s name), next it stores the object in a directory that’s name matches the first 2 characters of its hash, and finally names the remaining hash as the filename of the object. However, if a file(s) has the same hash then it won’t store the same file twice. This helps to reduce the amount of space used along with the default use of the zlib library for compression. Another thing that helps to reduce the amount of space used is the use of packs. Packs contain multiple objects, using delta compression for saving space. Below are 2 examples of how objects are stored in the .git directory:
.git/objects/02/b365d4af3ef6f74b0b1f18c41507c82b3ee571
.git/objects/37/ce98f6635fa1192d85243bcaa4622537b2eb87

Git also stores some metadata in the objects. This includes the files’ Unix permissions, every file revision (which are linked together to form a history), commit data (author, committer detail, timestamp, commit message, etc.), etc.

Git is primarily intended for use on Linux/Unix systems, however there are versions available for other operating systems, such as: BSD, OS X, Windows, and more. To find out more about git check out some of the links below.

External Resources:
• Gitscm.org – Official Website
• Pro Git Book – Official book (free)
• Git Quick Reference
• Git for Computer Scientists

## Functional Programming in JavaScript

Procedural programming is where you define a procedure to solve a problem. Functional (aka declarative) programming is distinct from this in that you describe the “what” of the problem. With functional programming the results depend upon only the inputs and not on the program state. JavaScript is actually a multi-paradigm language, because it supports object-oriented, imperative, and functional programming styles.

In JavaScript, functions are first-class and are objects themselves. This means that they can have properties and methods, which is similar to how classes have properties and methods in object-oriented programming. You can even nest functions within one another. This plus the prototypes offered by JavaScript allow for you to simulate class-based features of object-oriented languages.

In addition, there are a few features of JavaScript that help in programming in a functional style, a few of these are: anonymous functions, ability to use functions as values, and the ability for functions as parameters for other functions.

Example 1 – Procedural vs Functional
Procedural Version:
var paragraphs = mailArchive[mail].split(“\n”);
for (var i = 0; i < paragraphs.length; i++)
handlePara(paragraphs[i]);

Functional Version:
forEach(mailArchive[mail].split(“\n”), handlePara);

Example 2 – Self-Executing Anonymous Function
(function (name) {
console.log(name + ” functions can be automatically executed on defining them”)
})(“Anonymous”);
console.log(“JavaScript provides functional scope in place of block scoping”);
(function () {
if (true) {
var x = true;
console.log(“Is ‘x’ available inside block? ” + x);
}
console.log(“Is ‘x’ available outside block? ” + x);
})();

Example 3 – Using Functions as Parameters to Other Functions
function anim(property, duration, endCallback) {
if (typeof endCallback === ‘function’) {
endCallback.apply(null);
}
}
anim(‘background-color’, 1000, function () {
console.log(‘finished’);
});

Use functional programming techniques to write elegant JavaScript (ibm.com)
Functional Programming — Eloquent JavaScript
An Introduction to Functional Programming in JavaScript (srirangan.net)
\$bull; Functional Programming with JavaScript (blog.mgechev.com)

## JavaScript Functions as Object Constructors

JavaScript is a prototype-based language and doesn’t exactly support actual constructors, but we can sort of simulate constructors with functions. One thing to be weary of in JavaScript is scope management. JavaScript doesn’t support classes; it only has support for functions. So you would be using functions in place of classes as well. Also, scope can be an issue with the ‘this’ keyword because ‘this’ operates different than in object-oriented languages. In JavaScript, the ‘this’ keyword refers to the global scope (window object), whereas in most object-oriented languages ‘this’ refers to the parent object.

With those things in mind, we can craft a solution to the no-constructor and no-class situation. You can create instances of a function using the ‘new’ keyword, much like how you’d create instances of a class in object-oriented languages. We can actually use this method to fix the scope problem of the ‘this keyword’. When we create a new instance the ‘this’ keyword is then assigned the scope of the new function instance and no longer the window object. For example:

```function theFunction() {
this.doSomething = function() { //Here 'this' refers to window object
return message;
}
}
var myTheFunction = new theFunction(); //Here 'new' controls the scope
myTheFunction.doSomething();```

## Hidden features of: HTML, JavaScript, C#, VB, Java, Python, and more

These pages had been posted on StackOverflow a few years ago. They contain great collections of “hidden features” of various languages and even of a few tools.

Hidden Features of HTML
Hidden Features of JavaScript

Hidden Features of CSS
Hidden Features of C#
Hidden Features of VB.NET
Hidden Features of Java
Hidden Features of classic ASP
Hidden Features of ASP.NET
Hidden Features of Python
Hidden Features of TextPad
Hidden Features of Eclipse

## Quick-Find Algorithm in JavaScript

Here is my (quickly thrown together) simple implementation of the quick-find algorithm. For more information on the algorithm and the Disjoint-set data structure (quick-find performs some useful operations on this type of data structure) check out the Wikipedia page on Disjoint-set data structure here.

```var numArray;

function QuickFindUF(numToFind) {
numArray = new Array(numToFind);

for (var i = 0; i < numToFind; i++) {
numArray[i] = i;
document.write(numArray[i] + "<br/>");
}
}

function connected(p,q) {
return numArray[p] == numArray[q];
}

function union(p,q) {
var pid = numArray[p];
var qid = numArray[q];
for (var i=0; i < numArray.length();i++){
if (numArray[i] == pid) numArray[i] = qid;
}
}```

Tags: , , ,

## Optimizing Web Assets for Performance

Although most internet users nowadays have very fast connections it is still important to optimize your web application’s assets to ensure optimal performance. This is especially the case for mobile users, which have more constrained resources (data connections and hardware resources). There are a number of things you can do but I’lll highlight just a few that I believe are important to think about.

Images

Serve Multiple Sizes – Instead of serving the same image used in multiple locations at different sizes on your website, you should try to make use of CSS media queries to define separate images for certain circumstances. Check out css-tricks’s page on media queries for more info.

Compression – You should compress your images as well as possible in a photo editor before using them on the web. However, you can also use code to compress them on the fly. For example, this is possible using the various image processing utility functions in PHP.

Prefetching – With the new HTML5 specification you can prefetch content before its actually needed. This means that when it is needed, the content will already be available. Check out the WhatWG page on the prefetch specification for more info.

Caching – It’s a good idea to try to take advantage of caching in your browser if possible. This way you can reduce the amount of content that needs to be retrieved multiple times. To learn more about controlling your browser’s caching in the HTTP headers check out this page via betterexplained.com.

Stylesheets (CSS)

Preprocessing – CSS preprocessors help to automatically organize and optimize your stylesheets. Check out LESS, SASS, or Stylus.

Syntax Improvements – By carefully crafting your stylesheets you can reduce the size and increase the performance of rendering them. For some tips on good practices check out this developers.google.com site and this css-tricks.com page. You can also minimize the size of your CSS files automatically with tools such as CSSOptimizer and Minifycss.

Client-Side Code (JavaScript)

Size – You can also minimize the size of your JavaScript code. This reduced file size will allow for it to load quicker. There are quite a few tools out there to help you automatically minimize your JavaScript code.

Code Organization – You should try to only load code as its needed in your application. Minimizing HTTP requests will help to increase performance. You can make use of tools such as RequireJS to load different modules as needed. There are also ways to ‘simulate’ namespaces in JavaScript to help reduce the number of objects and to better organize the code.

Design Patterns – You wouldn’t want to create everything you want to do from scratch. For many things you want to do there are most likely established efficient methods out there. Some design patterns to look at may be: Constructor Pattern, Module Pattern, MVC Pattern, Observer Pattern, Function Chaining Pattern, etc.

## What Is Cross-Site Scripting (XSS) And How to Prevent It

Cross-Site Scripting (XSS) isn’t necessarily an actual “cross-site” attack, instead its essentially an insertion of client-side script code placed strategically such that users will execute them. This is possible when output from the website isn’t properly escaped, thereby allowing extra code to be added.

Ideally, at the appropriate times, you will want to escape both input and output from places like your database, however with XSS we’re primarily concerned with user input. One method of partially protecting against XSS (and also to prevent SQL injection) you can make use of magic quotes (at least in PHP), which will basically break (causing syntax error) any JavaScript code that may have been added.

There are also other ways to protect against XSS attacks. With PHP, when inserting HTML you can make use of the htmlspecialchars() function, which will convert special characters to HTML. This means that you won’t be able to insert additional JavaScript code because it would be encoded. For example, <script> would be encoded to &lt;script&gt;. There are still ways to get around this protection but it’s may be helpful to prevent some attacks. Another thing you can do would be to combine your input escaping with output escaping when storing and retrieving data from the database. With this you would escape characters going into the database and then both escape and encode (htmlspecialchars) on the retrieval. For example you would do something like this:

Input to Database
query_db(INSERT INTO the_table (column_name) VALUES (‘” . escape(\$_GET["column_name"]) . “‘));

Output From Database
echo HTMLSPECIALCHARS(query_db(“SELECT column_name FROM table_name WHERE id = value”));

Combine Input & Output Escaping
\$item = HTMLSPECIALCHARS(ESCAPE(\$_GET["column_name"]));
query_db(“INSERT INTO table_name (column_name) VALUES(‘\$item’)”);
echo query_db(“SELECT column_name FROM table_name WHERE id = ” . just_inserted_id());