简体   繁体   中英

javascript sets - adding value to array in object inside a set

I'm trying to make an array of sets to make something like this

{
    'user1': ["value#1", "value#2",..."value#N"],
    'user2': ["value#2",..."value#N"],
    'userN': [..."value#N"]
}

and then remove the value#x after 5 seconds (for example).

here is my code:

var myset = new Set();
var ran = myset[USERID] = commandNumber;

//i'm trying to make "if myset contains userNumber AND commandName" return, 
//if its not, run someFunction() and continue
if (myset.has(ran)) return;
someFunction();

myset.add(ran);
setTimeout(() => {
  myset.delete(ran);
}, 5000);

instead of getting output like the first code, i get this output instead

Set { 'command1', 'command2',
'USER1': 'command3',
'USER2': 'command4'
'USERN': 'commandN'
}

Feel free to comment if you have a question, so sorry if my question is hard to understand

A Set for this purpose is not necessary but I did a small POC that could help you to implement the solution you need:

'use strict';

const mySet = new Set();
const mySetMetadata = {};

const removeFromSet = (userKey, commandName) => {
  const commands = mySetMetadata[userKey] || [];
  if (commands.includes(commandName)) {
    mySetMetadata[userKey] = commands.filter(c => c !== commandName);

    if (mySetMetadata[userKey].length === 0) {
      mySet.delete(userKey);
      mySetMetadata[userKey] = undefined;
    }
  }
};

/**
 * Add relation between an userKey and a command
 * @param {String} userKey
 * @param {Array} commands Array of commands
 */
const addToSet = (userkey, commands) => {
  mySet.add(userkey);

  if (typeof mySetMetadata[userkey] === 'undefined') {
    mySetMetadata[userkey] = commands;
  } else {
    mySetMetadata[userKey] = [...mySetMetadata[userKey], ...commands]
  }  
}

// Populate with demo data
addToSet('user1', ['value#1', 'value#2', 'value#N']);
addToSet('user2', ['value#2', 'value#N']);
addToSet('user3', ['value#N']);

// Set up a timeout for a given user + key
setTimeout(() => {
  removeFromSet('user1', 'value#2');
}, 5000);

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