Month: December 2015

Arrays as Multipurpose Data Structures in JavaScript

In JavaScript the Array object is a very powerful data structure with it you can "simulate" other data structures, like Queues, Stacks, List, etc.

There is a list with some of the most important methods of the array object in JavaScript, we going to use them to create/simulate our data structures, you can see example of these methods in action, below.

Array.push(value1, value2, value3,…) – Add one or more Elements to the end of the array. This method will return the new length of it. You can specify multiple comma separated values.
Array.pop() – Removes the last element from an array and returns it.
Array.unshift(value1, value2, value3,…) – Add one or more elements to the beginning of the array. This method will return the new array length. You can specify multiple comma separated values.
Array.shift() – Removes the first element from an array and returns it.
Array.splice(splice(start, deleteCount[, item1[, item2[, ...]]])) - The splice() method changes the content of an array by removing existing elements and/or adding new elements.

Data Structures array

Other useful methods.

We are not going to use this methods to create the data structures showed in this post, but it might be handy.

Array.reverse() – Reverses the order by position (the first element becomes the last and the last one becomes the first, etc).

var arr = ['a', 'b', 'c'];
arr.reverse();
console.log(arr); //this will display ["c", "b", "a"]

Array.sort([compareFunction]) – Allows you to sort an array by specifying a compare function which has access to each value in the array you want to sort.

var arr = ['d', 'e', 'b', 'c', 'a'];
arr.sort(function(a, b){
  if (a < b) { return -1; } if (a > b){ return 1; }
  // a must be equal to b
  return 0;
});
console.log(arr); //this will display ["a", "b", "c", "d", "e"]
//Note: for this simple sort you can do arr.sort(), an you'll obtain the same result.

Array.join(separator) – This method takes one or more items in the array and returns a string of values joined by their separator. If you don’t specify a separator, the default is a comma.

var arr = ['a', 'b', 'c'];
var str = arr.join('-');
console.log(str); //this will display "c-b-a"

Array.indexOf(value) – This method allows you to find the first occurrence of the specified value, or –1 if not found.

var arr = ['a', 'b', 'c'];
if(arr.indexOf("a") > -1)
console.log('found "a" in arr');

 

book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

 

Data Structures

  • Arrays used as Queue

  • Arrays used as Stack

  • Arrays used as List

 

Arrays as Queue:

A queue follows the First-In First-Out (FIFO) paradigm: the first item added will be the first item removed. An array can be turned into a queue by using the push() and shift() methods. push() inserts the passed argument at the end of the array, and shift() removes and returns the first item, consider the following example:

function Queue(length) {
    var ret = [];

    ret.enqueue = function(a) {
        if(ret.length == length){
             ret.shift();
        }
        return Array.prototype.push.apply(this, arguments);
    };
    ret.dequeue = function(){
        return Array.prototype.shift.apply(this);
    }
    return ret;
}

var aux = Queue(3);
aux.enqueue('cat');
aux.enqueue('dog');
aux.enqueue('duc');
aux.enqueue('worm');
console.log(aux); // should contain dog, duc, worm
aux.dequeue();
console.log(aux);

Arrays used as Stack.

A stack follows the Last-In First-Out (LIFO) paradigm: an item added last will be removed first. The Array class has 2 methods that provide stack functionality. they are push() and pop(). push() appends an item to the end of the array, and pop() removes and returns the last item in the array
push(data) adds data.

pop() removes the most recently added data.

function Stack() {
    var ret = [];

    ret.push = function(a) {
        return Array.prototype.push.apply(this, arguments);
    };
    
    ret.pop = function(){
        return Array.prototype.pop.apply(this);
    }

    return ret;
}

var stack= Stack();
stack.push("A");
stack.push("B");
stack.push("C");
console.log(stack);
stack.pop();
console.log(stack);

Arrays used as List.

A List a collection of unsorted elements, where you can add or remove elements.

function List() {
    var ret = [];
    ret.add = function(element) {
        return Array.prototype.push.apply(this, arguments);
    };
    ret.remove = function(element){
        return Array.prototype.slice.apply(this, ret.splice(ret.indexOf(element), 1));
    }
    return ret;
}

var aux = List();
aux.add('cat');
aux.add('dog');
aux.add('duc');
aux.add('worm');
console.log(aux); 
aux.remove('dog');
console.log(aux);

Wrapping up:

As you can see the those three data structures queue, stack and list are simple arrays wrapped in a function to rename the methods used to add or remove elements from the collections with more semantic names. If you have any enhancement or any subjection please don't hesitate to share with us.

References to learn more:

developer.mozilla.org - Arrays

IQueryable VS IEnumerable in C#

As C# developers we use IEnumerable and IQueryable for data manipulation almost all the time in our application projects, and for me, sometimes is confusing when to use one or another. So I searched in internet and created the table bellow so if I forget I can quickly come to this post and review the differences so I can get the most of each and make sure I use it correctly.

IQueryable IEnumerable

IEnumerable IQueryable
Namespace. System.Collections System.Linq
Derives from. No base interface. Derives from IEnumerable.
Deferred Execution. Supported. Supported.
Lazy Loading. Not Supported. Suported.
Suitable for. LINQ to Object and LINQ to XML queries. LINQ to SQL queries.
Custom Query. Doesn’t supports. Supports using CreateQuery and Execute methods.
Other characteristics. It is a read only collection.
It iterates only in forward direction.
It works with collection in local memory.
It does not support adding, removing objects on collection.
It provides enumerator to iterate collection in forward direction.
It implements IEnumerable,so the results can be iterated using foreach.
It is best suited to query external data sources,(like remote database, service) collections.
It works with queryable data provider.
It creates query using an Expression Tree.
It is used to query a queryable data source.
When to use... Working with the read only collection.
Need to read the objects in forward direction only.
Not concerned about thread safety.
Want to iterate the collection’s objects using foreach.
Working with the queryable datasource.
Need to apply filter on data at the datasource.
Need to apply paging , composition.
Working with external data source.
Needs to load data in deferred way.
Need to use foreach to iterate collection.

IEnumerable Example:

DataContext ctx = new DataContext ();
IEnumerable<People> collection = ctx.People.Where(p => p.Name.StartsWith("j"));
collection = collection.Take<People>(20); 

Generated SQL statements of above query will be :

 SELECT [t0].[ID], [t0].[Name], [t0].[Salary] FROM [People] AS [t0]
WHERE [t0].[Name] LIKE @p0

Notice that in this query "top 20" is missing since IEnumerable place all the records in memory and filters on client side.

IQeryable Example:

 DataContext ctx = new DataContext ();
IQueryable<People> collection = ctx.People.Where(p => p.Name.StartsWith("j"));
collection = collection.Take<People>(20); 

Generated SQL statements of above query will be :

 
SELECT TOP 20 [t0].[ID], [t0].[Name], [t0].[Salary] FROM [People] AS [t0]
WHERE [t0].[Name] LIKE @p0

Notice that in this query "top 20" is exist, since IQueryable executes query in SQL server with all filters, and put in memory the result already filtered.

Official documentation for IQueryable and IEnumerable:

https://msdn.microsoft.com/en-us/library/system.linq.iqueryable(v=vs.100).aspx
https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx