Implementing vectors in JavaScript
Vector is one of the simplest data structures with the following properties:
- fixed size
- ordered: elements are arranged sequentially, one after the other
- finite size: zero or finite integer number of elements
This is similar to what arrays in C are and is easy to visualize how they relate to computer memory (sequentially arranged blocks to store data).
Vector Operations
new Vector(n) // create a vector n elements
LENGTH(v) // get the length of the vector, i.e. the number of elements
v[i] // read the value at index i
v[i] = o // store o at index i
I used arrays and objects in JavaScript to implement the above functionality.
JavaScript Implementation
// vector.js -- constructing vectors in JavaScript
function Vector(length)
{
this.length = length;
this.data = new Array(length);
}
v1 = new Vector(3); // create a new instance of Vector
console.log(v1);
// method to set the value of index i to x
Vector.prototype.set = function(x, i)
{
if (i < this.length)
this.data[i] = x;
else
console.log("Error! Index out of bounds: " ,
i , "> " , this.length - 1);
}
// testing the set method
for (var i = 0; i < v1.length; i++)
v1.set(i*i - i, i);
console.log(v1);
v1.set(15, 13); // cannot assign 15 since index(13) is out of bounds
// method to get the value of index i
Vector.prototype.get = function(i)
{
if (i < this.length)
console.log(this.data[i]);
else
console.log("Error! Index out of bounds: " ,
i , "> " , this.length - 1);
}
// testing the get method
v1.get(2);
v1.get(5);
Output
Vector { length: 3, data: [ <3 empty items> ] }
Vector { length: 3, data: [ 0, 0, 2 ] }
Error! Index out of bounds: 13 > 2
2
Error! Index out of bounds: 5 > 2