Creating an IO object
After nearly giving up and getting some hints from Dr. Shawn, I finally achieved my small task. As I am working on a virtual processor in Javascript, I am required to enhance the LW and SW instructions to be able to handle IO instructions on port-mapped addresses. There are a set of predefined addresses which are used to store the information of the IO. So, it is important that the IO addresses are being handled correctly. But how does the processor know which address to handle differently? That is where a “dictionary object” comes into place. In javascript, we can implement this by
var dictionaryObject =
{
1000: run_function1;
2000: run_function2;
};
This can be used in many ways. First, we can run it by dictionaryObject[1000](arguments);
(run_function1 is executed)
Second, we can check if the dictionary contains the object by implementing
if(dictionaryObject[1000]){
dictionaryObject1000;
}
I nearly give up because I did not understand how Javascript OOP works. I kept storing the function at the address, where in fact, I can store the IO object. So, I forgot to mention another way of using the dictionary object is that new members can be added during runtime. Knowing the addresses of the IO, a predefined mapping can be constructed. As to storing the object at the address, this does the trick:
objMapping={}; // an empty "dictionary object"
// In the IO constructor
function IO(addr) {
...
objMapping[addr]= this.data; // this creates a new member in objMapping labeled with 'addr'
};
//Finally, in the LW/SW function
if (objMapping[addr]){
objMappping[addr].save(val); // where save is a method of the object.
}
The end product is a really short and concise piece of code, as compared to more than 200 lines of code, fully utilizing OOP in Javascript reduced the lines more than half, and abolished pointless looping by switch..case and if… else statements.
0 Comments