Search code examples
javascriptclassinstance

Can you pass a handle to a class instance in JavaScript?


I am pretty new to JavaScript. I have a NodeJS express app which creates an array of instances of a class. I want to provide a client with a handle to an instance so that the server does not have to find the instance by ID for every API call. The array index may change as instances are deleted. Is there a clean way of doing this?


Solution

  • Instead of using an array, consider using a Map or object, for which key lookup is sublinear (and much faster than using findIndex with an array). For example, rather than

    const handles = [];
    
    // when you need to add an item:
    handles.push(new Handle(1234));
    
    // when you need to retrieve an item:
    const handle = handles.find(obj => obj.id === id)
    // will be undefined if no such handle exists yet
    

    do

    const handles = new Map();
    
    // when you need to add an item:
    handles.set(1234, new Handle(1234));
    
    // when you need to retrieve an item
    const handle = handles.get(id);
    // will be undefined if no such handle exists yet
    

    There's no need to worry about re-indexing with this approach either.