user5405648
user5405648

Reputation:

Store function with ID as a key in JavaScript?

I have lots of packets that come through to my javascript via web sockets, each of these packets have a packet id, I want to create some sort of array or object that assigns each packet id a function to call, which would handle that packet.

I also want to include the 'packetData' parameter to all functions that are called, so it can get the other parts of data inside the function in order to handle the packet appropriately.

Heres what I have so far...

I listen for a message on WebSockets...

socket.onmessage = function (e) {
    onPacket(JSON.parse(e.data));
};

Then I pass it to this function, I send my data in JSON format so I parse it to a key value object, then pass it to this function...

function onPacket(packetData) {
    const packetId = packetData['packet_id'];
    // TODO: Call the function...
}

The part I am stuck with is how do I create the array or keyvalue object to call the function? I store all my functions in a seperate file called "packet_events.js"

I did have a go at doing it myself (the object key value) but I was told it isn't valid JS, I'm stuck and sort of need some help, can anyone help?

My attempt:

var incomingHeaders = {
    1: packetOne(),
};

If I still haven't made it clear, I want something like this, but with an array to save me constantly writing if statements..

function onPacket(packetData) {
    const packetId = packetData['packet_id'];

    if (packetId == 1) {
        packetOne(packetData);
    }

    if (packetId == 2) {
        packetTwo(packetData);
    }

    if (packetId == 3) {
        packetThree(packetData);
    }
}

Upvotes: 2

Views: 321

Answers (2)

nitte93
nitte93

Reputation: 1840

Step 1: Create a function object that holds mapping from your packedId to your function.

Step 2: Iterate over the packets array to call the respective function.

Follow the snippet:

function packetOne() {
  console.log('one')
}

function packetTwo() {
  console.log('two')

}

let functionObject = {
	1: packetOne,
	2: packetTwo,
}


let packets = [
{ packetId: 1},
{ packetId: 2}
]

packets.forEach(function(packet){
 functionObject[packet.packetId]()
})

Upvotes: 0

Bartosz Matuszewski
Bartosz Matuszewski

Reputation: 203

Use object instead of arrays and create maping of ids into functions e.g.

var idToFunction = {
   0:  packetOne,
   1:  packetTwo,
   2:  packetThree
}

then inside onPacket your retrievied function based on id and executes it

function onPacket(packetData) {
    const packetId = packetData['packet_id'];
    var processPacket = idToFunction[packetId];

    if (processPacket) {
        processPacket(packetData);
    }
    else {            
        throw new Error("Invalid packed id: "+packetId);
    }
}

Upvotes: 1

Related Questions