Wednesday, March 27, 2013

Data Structures

This post is written for people who are familiar with the basics of computer science and a little javascript. If this is not you, feel free to read the code below (which contains extra comments.)

There is an entire field within computer science dedicated to finding efficient ways to store information. I was not satisfied with how I was storing data in an early version of fractal canvas, specifically how points in the template needed frequent updates to keep them in sync with their representations under the hood. My solution is to create a data structure that stores each point with an Id that is unique for the lifetime of the page.

Warning: it gets more technical


//hashedArray is my new data structure gives each element an ID that is unique for the lifetime of the page
function hashedArray(){
    this.id = 0; //the ID of the newly inserted element
    this.elements = []; //holds the data
    
    //gets the length of the elements (needed because array is sparse)
    this.length = function(){
        var cnt = 0;
        for(var i in this.elements) cnt++;
        return cnt;
    };
    
    //index is optional - defaults to the end of the array
    this.insert = function(elem, index){
        index = ((typeof index === 'undefined') ? this.elements.length : index);
        this.elements.splice(index, 0, {hash: this.id, data: elem});
        return this.id++;
    };
    
    //getter
    this.get = function(){
        return this.elements.map(function(elem){ return elem.data; })
    };
    
    //get an element by its hash
    this.getElementByHash = function(hash){
        for(var elem in this.elements) if(this.elements[elem].hash === hash) return this.elements[elem]; //find the element
    };
}
//create an object to hold the sketch points
this.sketchPoints = new hashedArray();

No comments:

Post a Comment