0

I have an upload handler connected to my js script.

(This upload handler is written in c++ and thus I'm unable to pass js objects around)

this upload handler starts the upload and immediately returns an UID (based on the current timestamp in milliseconds. looks like this :

var transferUid = fileTransfers.addFileTransfer(sourcePath,destination);

I'd like to add a callback function to this. When the transfer is finished. This js function is automatically executed when finished :

filetransfersfinished(uid){...}

is it reasonable to do something like this :

var finishFunctions = [];
finishfunctions [transferUid] = function(){/*callbacks*/}

transferUid could be like 184548178452 ...

and call it when the automatic function is called :

filetransfersfinished(uid){  finishfunctions[uid]();  }

Or is there a better solution you can think of?

Vincent Duprez
  • 3,772
  • 8
  • 36
  • 76

1 Answers1

2

Answering the question

Using Heap profiling tools in chrome, giving an array a huge size for little content does not seems to cause problems or a peak in heap allocation.

That's confirmed here as "Sparse Arrays vs. Full Arrays", and confirmed with this jsperf.

In substance : sparse arrays are slow, but not expected to be slower than objects properties.

Anyway, i'd suggest you use objects as it's more intuitive :

Answering your particular case

Best way would be to use an object (javascript equivalent to an "associative array") as pointed out in comment. There is many ways to do it but to keep the syntax you used as much as possible, i'd do it like this :

var finishFunctions = {};
finishfunctions [transferUid.toString()] = function(){/*callbacks*/}

And then your callback :

filetransfersfinished(uid){  finishfunctions[uid.toString()]();  }

Note: With this method, you could use any convenient format for your uid, not just numbers. If it's of any value for you.

Community
  • 1
  • 1
sdumetz
  • 552
  • 2
  • 11
  • Thanks for checking the perfs. I will indeed use an object by adding a letter to the UID returned, so there is no confusion between a stringified int and a int. – Vincent Duprez Dec 10 '14 at 09:42