skip to Main Content

Is there any similar implementation of ‘unordered_set’ / ‘unordered_map’ from c++, in javascript?

C++ Implementation

void someFunction(vector<int> &arr, int k){
    unordered_set<int> s(arr.begin(), arr.end());
    
    auto it = s.find(k); // TC: O(1)
    if(it != s.end())
        s.erase(k); // TC: O(1)
    else
        s.insert(k); // TC: O(1)
}

JS alternative try…

function someFunction(arr, k){
    let s = new set(arr);
    
    if(s.has(k)) // TC = ?
        s.delete(k); // TC = ?
    else
        s.add(k); // TC = ?
}

2

Answers


  1. You are close but you made it set where it should have been Set. See Set @ Mozilla.

    function someFunction(arr, k) {
      s = new Set(arr);
    
      if(s.has(k)) {
        console.log("deleting ", k);
        s.delete(k);
      } else {
        console.log("adding ", k);
        s.add(k);
      }
      
      return s;
    }
    
    var res = someFunction([1,2,3,4], 5);
    console.log(Array.from(s)); // 1,2,3,4,5
    Login or Signup to reply.
  2. TLDR: The javascript object type is effectively a map.

    let arr = [33,44,55,66];
    let s = {}; // object declaration
    let j = 33;
    let k = 99;
    
    // enumerate array and insert values
    for (item of arr) {
        s[item] = true;
    }
    
    // search: s[item] will return undefined if item is not in object's map
    // otherwise, if found, it will return the value at that key
    
    console.log("j was " + (s[j] ? "found" : "not found"));
    console.log("k was " + (s[k] ? "found" : "not found"));
    
    // remove
    delete s[j];
    
    // insert
    s[k] = true
    
    console.log("-----");
    console.log("j was " + (s[j] ? "found" : "not found"));
    console.log("k was " + (s[k] ? "found" : "not found"));

    Also of note – Arrays are objects too in Javascript, So the array: [33,44,55,66] is mostly equivalent to:

    arr = {};
    arr[0] = 33;
    arr[1] = 44;
    arr[2] = 55;
    arr[3] = 66;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search