简体   繁体   中英

Extended Array Class in Javascript: How should I create helper functions to modify Array without assigning a new reference?

This is a socket.io lobby library for managing the users list.
I created an Array extension class with custom methods. My removeUser method does not work. Logging shows that inside of the method, it does work - the user has been removed. Logging outside shows no change.

I believe my issue is one of references. The reference in index.js 'userList' is one reference.
var userList = require("./userList")();
However when I reassign userList in the method, it creates another reference.
userArray = result;
This newly-created reference is not known by the index.js, which sees no change in the userList object.

index.js My server (simplified for example)

const express = require("express");
const bodyParser = require("body-parser");
const app = express();

const server = require("http").createServer(app);
const io = require("socket.io")(server);

var userList = require("./userList")();

io.on("connection", (socket) => {
  // get user from session
  userList.addUser(s_user);
  socket.on("disconnect", () => {
    userList.removeUser(s_user);
  });
});

userList.js (Original) An extended Array class for managing the list of users in my lobby.

function createUserList() {
  
  let userArray = [];

  userArray.addUser = (user) => {
    userArray.push(user);
  };

  userArray.removeUser = (user) => {
    let userId = user.user_id;
    for (let i = 0; i < userArray.length; i++) {
      if (userArray[i]["user_id"] === userId && userId !== undefined) {
        let firstHalf = userArray.slice(0, i);
        let secondHalf = userArray.slice(i+1, userArray.length);
        let result = firstHalf.concat(secondHalf);
        userArray = result;
      }
    }
  };

  return userArray;
}

My Solution
My solution was to create a closure. An array manager object contains the methods for userList management, and through a closure has access to the userArray. (code below this paragraph)
Pros

  • The userArray can modified or reassigned without reference issue (within the userList library)
    userArray = [] //ok
    (I also don't have to re-attach methods on re-assignment)

Cons

  • I can't use Array prototype methods
    let length = userList.length // method doesn't exist on management object
    let listCopy = userList // returns an object, not the list
    I must use my custom built methods
    let length = userList.getLength()
    let listCopy = userList.getList()

Does anyone have other interesting solutions?

userList.js (V2)

function createUserList() {

  let userArray = []

  let arrayManager = {

    addUser: (user) => {
      userArray.push(user);
    },

    removeUser: (user) => {
      let userId = user.user_id;
      for (let i = 0; i < userArray.length; i++) {
        if (userArray[i]["user_id"] === userId && userId !== undefined) {
          let firstHalf = userArray.slice(0, i);
          let secondHalf = userArray.slice(i+1, userArray.length);
          let result = firstHalf.concat(secondHalf);
          userArray = result;
        }
      }
    },

    getList: () => {
      return userArray;
    },

    getLength: () => {
      return userArray.length;
    }
  };

  return arrayManager;
}

module.exports = createUserList;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM